[英]Add multiple values to single key in python dictionary
我将使用python读取文本文件,并尝试创建包含唯一键和多个值的字典。
码:
f = open("address.txt", 'r')
email = {}
for line in f:
k, v = line.strip().split()
if k.strip() in email:
email[k.strip()].append(v.strip())
else:
email[k.strip()] = [v.strip()]
print email
f.close()
输入:
user1@abc.com 192.168.56.3 hostname5
user2@xyz.com 192.168.56.4 hostname2
user1@abc.com 192.168.56.5 hostname3
user2@xyz.com 192.168.56.7 hostname1
user1@abc.com 192.168.56.6 hostname4
user1@abc.com 192.168.56.9 hostname3
预期产量:
user1@abc.com 192.168.56.3 hostname5 192.168.56.5 hostname3 192.168.56.6 hostname4 192.168.56.9 hostname3
user2@xyz.com 192.168.56.4 hostname2 192.168.56.7 hostname1
我收到错误消息:
Traceback (most recent call last):
File "final.py", line 4, in <module>
k, v = line.strip().split()
ValueError: too many values to unpack
我不知道代码有什么问题? 提前谢谢你的帮助。
为了使您的生活更轻松,您可以使用dict.setdefault
或collections.defaultdict
:
import collections
email = collections.defaultdict(list)
with open("address.txt", 'r') as f:
for line in f:
k, *v = line.strip().split() # use catch all unpacking here
email[k].append(tuple(v))
email
是key : list of values
字典key : list of values
对key : list of values
。 看起来是这样的:
defaultdict(list,
{'user1@abc.com': [('192.168.56.3', 'hostname5'),
('192.168.56.5', 'hostname3'),
('192.168.56.6', 'hostname4'),
('192.168.56.9', 'hostname3')],
'user2@xyz.com': [('192.168.56.4', 'hostname2'),
('192.168.56.7', 'hostname1')]})
如果您想进一步采取行动,并以问题中指定的确切格式获取数据(尽管您几乎无法使用这种形式的数据),请按以下步骤操作( 谢谢Alexander! ):
In [486]: {k: [" ".join([" ".join(tup) for tup in email[k]])] for k in email}
Out[486]:
{'user1@abc.com': ['192.168.56.3 hostname5 192.168.56.5 hostname3 192.168.56.6 hostname4 192.168.56.9 hostname3'],
'user2@xyz.com': ['192.168.56.4 hostname2 192.168.56.7 hostname1']}
您需要将从每一行读取的三个值存储到三个变量中,而不是两个。 尝试:
f = open("address.txt", 'r')
email = {}
for line in f:
k, v, a = line.strip().split()
if k.strip() in email:
email[k.strip()].append(v.strip())
email[k.strip()].append(a.strip())
else:
email[k.strip()] = [v.strip(), a.strip()]
print email
f.close()
line.split()
返回一个包含3个要存储在2个元素中的列表,可以避免这种情况,方法是先分割线,然后对其进行切片以获得两个变量。 使用split()
时,也不需要使用strip()
split()
。 例如:
with open("address.txt", 'r') as f:
email = {}
for line in f:
line = line.split()
k, v = line[0], line[1:]
email[k] = email.get(k, []) + v
# instead of using if/else, email.get(k, []) returns the value if available or an empty list if not
for k, v in email.iteritems():
print('{} {}'.format(k, ' '.join(v)))
输出:
user2@xyz.com 192.168.56.4 hostname2 192.168.56.7 hostname1
user1@abc.com 192.168.56.3 hostname5 192.168.56.5 hostname3 192.168.56.6 hostname4 192.168.56.9 hostname3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.