2017-01-20 36 views
0

我有一個初始化的詞典,如:姓名的Python:更新與新名單值的初始化字典爲每個鍵

nemas = {'PERSON' : '', 'ORGANIZATION':'' , 'LOCATION': ''} 

和三個列表:

person_names = [u'Albert Einstein', u'Hermann Einstein', u'Pauline Koch', u'Einstein', u'Jakob'] 
organization_names = [u'Elektrotechnische Fabrik J. Einstein & Cie'] 
location_names = [u'Ulm', u'Kingdom of Britain', u'Munich'] 

我打算更新字典並獲得:

names = { 'PERSON' : [u'Albert Einstein', u'Hermann Einstein', u'Pauline Koch', u'Einstein', u'Jakob'], 
'ORGANIZATION': [u'Elektrotechnische Fabrik J. Einstein & Cie'], 
'LOCATION': [u'Ulm', u'Kingdom of Britain', u'Munich'] } 

我想:

name_dict = {"PERSON":dict(person_names), "ORGANIZATION": dict(organization_names), "LOCATION":dict(locatoin_names)} 
print(names.update(name_dict)) 

但它沒有工作。有沒有Pythonic方法來解決這個問題?

+0

你的第一部字典給出了一個語法錯誤得到預期的輸出。 – RemcoGerlich

+0

'nemas = {'PERSON':,'ORGANIZATION':,'LOCATION':}'是無效的python ... –

+0

我糾正了它,謝謝 –

回答

1

比方說,我們忽略你的第一行:

nemas = {'PERSON' : , 'ORGANIZATION': , 'LOCATION': }

你根本無法做到這一點。但你可以做

nemas = {'PERSON' : None, 'ORGANIZATION': None, 'LOCATION': None} 

然後最後你想要的是一個列表字典,但你試圖做一個字典的字典。試試這個:

name_dict = {"PERSON":person_names, "ORGANIZATION": organization_names, "LOCATION":location_names} 

請注意,我修正了一些錯別字。 然後你就可以

print(name_dict)