2017-06-16 60 views
-1

我试图用钥匙到另一个值加入到嵌套的字典,我有下面的代码,但它不能正常工作通过Python的关键

Content is a file with: 
a,b,c,d 
a,b,c,d 
a,b,c,d 

dict = {} 

for line in content: 
    values = line.split(",") 
    a = str.strip(values[0]) 
    b = str.strip(values[1]) 
    c = str.strip(values[2]) 
    d = str.strip(values[3]) 

    if a not in dict: 
     dict.update({a: {'Value1': b, 'Value2': c, 'Value3': d}},) 
    else: 
     dict[a]['Value1'].update(b) 

我希望它看起来追加到嵌套的字典中的多个值像:

a {'Value1': 'b,b,b', 'Value2': 'c', 'Value3': 'd'} 

我在做什么错?

+0

请将“content”的内容添加到您的问题中。 –

+0

不是什么大不了的,但是你可以在'line.split()]中编写'a,b,c,d = [x.strip(),这样看起来更加pythonic :) – Ding

+0

@Ding'.split ',')'* –

回答

1
dictionary = {} 

for line in content: 
    values = line.split(",") 
    a = str.strip(values[0]) 
    b = str.strip(values[1]) 
    c = str.strip(values[2]) 
    d = str.strip(values[3]) 

    if a not in dictionary.keys(): 
     dictionary = {a: {'Value1': b, 'Value2': c, 'Value3': d}} # creates dictionary 
    else: 
     dictionary[a]['Value1'] += ','+b # accesses desired value and updates it with ",b" 
print(dictionary) 
#Output: {'a': {'Value1': 'b,b,b', 'Value2': 'c', 'Value3': 'd'}} 

这应该做你的伎俩。您必须在else语句中添加',',因为您在使用时删除了它。split(',')

0

你不太明白update确实;这是replacement,不是附加。试试这个,而是:

if a not in dict: 
    dict.update({a: {'Value1': b, 'Value2': c, 'Value3': d}},) 
else: 
    dict[a]['Value1'] += ',' + b 

输出:

a {'Value3': 'd', 'Value2': 'c', 'Value1': 'b,b,b'} 

如果你想保留Value子字段的顺序,然后使用OrderedDict