用Python创建带有列表列表的字典 [英] Creating a dictionary with list of lists in Python

查看:496
本文介绍了用Python创建带有列表列表的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大文件(大约有20万个输入).输入的格式为:

I have a huge file (with around 200k inputs). The inputs are in the form:

A B C D
B E F
C A B D
D  

我正在读取此文件并将其存储在列表中,如下所示:

I am reading this file and storing it in a list as follows:

text = f.read().split('\n')

每当看到新行时,它将拆分文件.因此,文本如下所示:

This splits the file whenever it sees a new line. Hence text is like follows:

[[A B C D] [B E F] [C A B D] [D]]

我现在必须将这些值存储在字典中,其中键值是每个列表中的第一个元素.即键将是A,B,C,D. 我发现很难将值输入为列表的其余元素.即字典应如下所示:

I have to now store these values in a dictionary where the key values are the first element from each list. i.e the keys will be A, B, C, D. I am finding it difficult to enter the values as the remaining elements of the list. i.e the dictionary should look like:

{A: [B C D]; B: [E F]; C: [A B D]; D: []}

我已经执行以下操作:

    inlinkDict = {}
    for doc in text:
    adoc= doc.split(' ')
    docid = adoc[0]
    inlinkDict[docid] = inlinkDict.get(docid,0) +  {I do not understand what to put in here}

请帮助我如何将值添加到字典中.如果列表中没有任何元素(除了将作为键值的元素),则应为0.就像在0的示例中一样.

Please help as to how should i add the values to my dictionary. It should be 0 if there are no elements in the list except for the one which will be the key value. Like in example for 0.

推荐答案

尝试使用切片:

inlinkDict[docid] = adoc[1:]

对于仅键值在线的情况,这将为您提供一个空列表,而不是0.要获取0,请使用or(始终返回操作数之一):

This will give you an empty list instead of a 0 for the case where only the key value is on the line. To get a 0 instead, use an or (which always returns one of the operands):

inlinkDict[docid] = adoc[1:] or 0


一种简单的字典理解方法:


Easier way with a dict comprehension:

>>> with open('/tmp/spam.txt') as f:
...     data = [line.split() for line in f]
... 
>>> {d[0]: d[1:] for d in data}
{'A': ['B', 'C', 'D'], 'C': ['A', 'B', 'D'], 'B': ['E', 'F'], 'D': []}
>>> {d[0]: ' '.join(d[1:]) if d[1:] else 0 for d in data}
{'A': 'B C D', 'C': 'A B D', 'B': 'E F', 'D': 0}

注意:dict键必须是唯一的,因此,如果您有以'C'开头的两行,则第一行将被覆盖.

Note: dict keys must be unique, so if you have, say, two lines beginning with 'C' the first one will be over-written.

这篇关于用Python创建带有列表列表的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆