[英]Pack dictionary with values separated by comma
I have a text file like this: 我有一个这样的文本文件:
key1 value1 A
key1 value2 B
key1 value3 A
key2 value1 A
key2 value2 B
I am trying to open it as a dictionary and print the list of keys and values separated by commas so it looks like this in the end: 我正在尝试将其作为字典打开,并打印以逗号分隔的键和值的列表,因此最终看起来像这样:
key1 value1,value2,value A,B,A
key2 value1,value2,value A,B
I am trying the following code: 我正在尝试以下代码:
f = open('file.txt', 'r')
answer = {}
for line in f:
list = ",".join(map(str,f))
print list
But it's not working 但这没用
Any ideas what I am doing wrong? 有什么想法我做错了吗? Thanks for your help
谢谢你的帮助
Using collections.defaultdict
: 使用
collections.defaultdict
:
from collections import defaultdict
with open('file.txt') as f:
answer = defaultdict(lambda: ([], []))
for line in f:
key, value, alpha = line.split()
answer[key][0].append(value)
answer[key][1].append(alpha)
for key, (values, alphas) in sorted(answer.items()):
print key, ','.join(values), ','.join(alphas)
output: 输出:
key1 value1,value2,value3 A,B,A
key2 value1,value2 A,B
You are initializing a dictionary, but then you never use it in the loop. 您正在初始化字典,但随后您再也不会在循环中使用它了。 Try this approach instead:
请尝试以下方法:
from collections import defaultdict
answers = defaultdict(list)
with open('file.txt') as inf:
for line in inf:
bits = line.rstrip().split()
answers[bits[0]].append(','.join(bits[1:]))
for key,values in answers.iteritems(): # in Python 3, use answers.items()
for value in values:
print('{} {}'.format(key, value))
Also, don't use list
as the name of a variable. 另外,请勿将
list
用作变量的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.