2017-06-16 58 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