在python字典中为单个键添加多个值

时间:2017-08-10 04:29:04

标签: 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

我不知道代码有什么问题?感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

为了让您的生活更轻松,您可以使用dict.setdefaultcollections.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))

emailkey : 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')]})

如果您想采取进一步措施,并按照问题中指定的确切格式获取数据(尽管您可以使用此表单中的数据进行处理),请按照以下方式进行操作({{ 3}}):

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

答案 1 :(得分:0)

您需要将从每行读取的三个值存储到三个变量中,而不是两个变量中。尝试:

B

答案 2 :(得分:0)

line.split()返回一个包含3个元素的列表,您尝试将其存储在2中,您可以通过首先拆分行然后将其切片以获得两个变量来避免这种情况。使用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
相关问题