Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

Creating a dictionary with list of lists in Python

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('
')

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]]

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: []}

I have done the following:

    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}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A dictionary comprehension makes short work of this task:

>>> s = [['A','B','C','D'], ['B','E','F'], ['C','A','B','D'], ['D']]
>>> {t[0]:t[1:] for t in s}
{'A': ['B', 'C', 'D'], 'C': ['A', 'B', 'D'], 'B': ['E', 'F'], 'D': []}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...