简体   繁体   English

从文本文件创建字典并使用键作为输入获取值

[英]creating a dictionary from a text file and getting values from using key as input

I am trying to create a dictionary from an existing text file but this should be done automatically so for example I have this text file我正在尝试从现有文本文件创建字典,但这应该自动完成,例如我有这个文本文件

0 1
0 3
1 2

now I want to create this dictionary现在我想创建这本字典

a={
"0": "1","3"
"1": "0","2"}

which way should I follow to create this dictionary so when I add an input that is going to ask for a value that one is going to be the key and display the values?我应该遵循哪种方式来创建这个字典,所以当我添加一个输入将要求一个值时,一个将成为键并显示值?

I tried something with creating a list of all the keys and then adding the values from the text file but it only gives one value that is linked so for example it displays only我尝试创建一个包含所有键的列表,然后从文本文件中添加值,但它只给出一个链接的值,例如它只显示

"0": "1"

and not并不是

"0": "1","3"

You can try this:你可以试试这个:

from collections import defaultdict

a = defaultdict(list)
with open('text_file.txt', 'r') as f:
    for line in f:
        key, value = line.strip().split()
        a[key].append(value)
print(a)

Use setdefault() to initialize each key to an empty list and append the value from that row.使用setdefault()将每个键初始化为一个空列表,并将 append 初始化为该行的值。

a = {}

for line in file:
    key, value = line.split()
    a.setdefault(key, []).append(value)

print(a)

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

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