简体   繁体   English

在Python中将txt文件转换为字典

[英]Convert txt file to Dictionary in Python

I have a txt file that contain the following:我有一个包含以下内容的txt文件:

Monday, 56星期一,56

Tuesday, 89星期二,89

Wednesday, 57星期三,57

Monday, 34星期一,34

Tuesday, 31星期二, 31

Wednesday, 99星期三, 99

I need it to be converted to a dictionary:我需要将其转换为字典:

{'Monday': [56 , 34], 'Tuesday': [89, 31], 'Wednesday': [57, 99]} {'星期一':[56, 34],'星期二':[89, 31],'星期三':[57, 99]}

Here is the code I have so far:这是我到目前为止的代码:

d = {}
with open("test.txt") as f:
    for line in f:
        (key, val) = line.split()
        d[str(key)] = val
        print(d)

And here is the result I get from it:这是我从中得到的结果:

{'Monday,': '56'} {'星期一':'56'}

{'Monday,': '56', 'Tuesday,': '89'} {'星期一,':'56','星期二,':'89'}

{'Monday,': '56', 'Tuesday,': '89', 'Wednesday,': '57'} {'星期一,':'56','星期二,':'89','星期三,':'57'}

{'Monday,': '34', 'Tuesday,': '89', 'Wednesday,': '57'} {'星期一,':'34','星期二,':'89','星期三,':'57'}

{'Monday,': '34', 'Tuesday,': '31', 'Wednesday,': '57'} {'星期一,':'34','星期二,':'31','星期三,':'57'}

{'Monday,': '34', 'Tuesday,': '31', 'Wednesday,': '99'} {'星期一,':'34','星期二,':'31','星期三,':'99'}

Can anyone help me with this?谁能帮我这个?

Thanks谢谢

When you split the line you can use comma as a separator.拆分行时,您可以使用逗号作为分隔符。 Then after splitting the line you can check the dictionary on whether it already contain the key:然后在拆分行后,您可以检查字典是否已包含键:

(key, val) = line.split(',')
if key in d.keys:
    d[str(key)].append(val)
else:
    d[str(key)] = [val]
print (d)
d = {}

with open("test.txt") as f:
  for line in f:
    (key, val) = line.split()
    if not key in d.keys():
      d[key] = []

    d[key].append(val)

print (d)

This should work.这应该有效。

d = {}
with open("test.txt") as f:
    for line in f:
        (key, val) = line.split()
        if key in d:
            d[str(key)].append(val)
        else:
            d[str(key)] = [val]
print(d)

Try to add list of value in dictionary.尝试在字典中添加值列表。

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

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