简体   繁体   中英

convert tuples into a dictionary in python

I am working on a project which involves use of igraph and reading data from sqlite3 database.

Following are the column names in my database -

['id', 'title', 'authors', 'year', 'pub_venue', 'ref_id', 'ref_num', 'abstract']

where id is an integer type and ref_id is text having comma separated ref_ids.

The final goal is to create a graph in igraph using above data, where id is a vertex value and ids in ref_id will be used to create edges. If I enumerate every id to create vertices in igraph followed by enumeration of ids again to create edges, the performance will be hit badly.

Hence decided to convert list of tuples to dictionary using row['id'] as key and row['ref_id'] as value and using this dictionary to create graph in igraph.

in below also I am getting error -

b = {}
for row in list(res):
key = row['id']
val = 0
if row['ref_id'] != None:
    val = map(int, row['ref_id'].split(","))
b[key] = val

ValueError: invalid literal for int() with base 10: ''

What will be the fastest way to achieve it and why I am getting above error?

Let me know if the query requires any more detail.

The error means that one of the elements of row['ref_id'].split(";") is not convertible to an integer. In particular, it is empty '' according to the error.

This could be caused by whitespace as the other answers suggest. But I also noticed that in the text you say split by commas but in the code you split based on semicolon (";")`?

Really you should be able to figure this out just by printing the contents of row['ref_id'].split(";") before attempting to convert it to int. Also as a minor nitpick, just replace row['ref_id'] with key since you defined it already..

Use row['ref_id'].strip().split(";") to avoid annoying whitespaces. This should solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM