简体   繁体   English

在python中将元组转换为字典

[英]convert tuples into a dictionary in python

I am working on a project which involves use of igraph and reading data from sqlite3 database. 我正在从事一个涉及使用igraph和从sqlite3数据库读取数据的项目。

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. 其中id是整数类型,而ref_id是具有逗号分隔的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. 最终目标是使用上述数据在igraph中创建图形,其中id是顶点值,而ref_id中的id将用于创建边。 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. 如果我枚举每个id以在igraph中创建顶点,然后再次枚举id以创建边,则性能将受到严重影响。

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. 因此,决定使用row['id']作为键和row['ref_id']作为值,并使用此字典在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: '' ValueError:以10为底的int()的无效文字:''

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. 该错误意味着row['ref_id'].split(";")的元素之一无法转换为整数。 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. 确实,您应该能够在尝试将row['ref_id'].split(";")转换为int之前,将其内容打印出来。 Also as a minor nitpick, just replace row['ref_id'] with key since you defined it already.. 同样作为次要的nitpick,只需将row['ref_id']替换为key因为您已经定义了它。

Use row['ref_id'].strip().split(";") to avoid annoying whitespaces. 使用row['ref_id'].strip().split(";")避免烦人的空格。 This should solve your problem. 这应该可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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