[英]How to map values from a list to nested dictionaries in Python?
我有一個值列表和一個字典詞典。 他們看起來像這樣:
d = {1 : {1 : '', 2 : '', 3 : ''},2 : {1 : '', 2 : '', 3 : ''}}
l = ['Erich Martin', 'Zia Michael', 'Olga Williams', 'Uma Gates']
我正在嘗試將列表中的值映射到字典中,然后再填充到下一個嵌套字典,然后填充每個字典。 最后一個字典將有一些空插槽,這很好。 我似乎無法全神貫注於需要做的事情。 由於沒有更多值,因此我遇到了列表的末尾並遇到鍵盤錯誤。 這是我到目前為止的要點:
for g,s in d.items():
for i in s:
s[i] = l.pop()
使用Python 3.4。
謝謝!
嘗試這個:
根據ikaros45的評論進行編輯
for g,s in d.items():
for i in s:
if not l:
break
s[i] = l.pop()
這將產生:
{1: {1: 'Uma Gates', 2: 'Olga Williams', 3: 'Zia Michael'}, 2: {1: 'Erich Martin', 2: '', 3: ''}}
您正在遍歷字典時對其進行修改。 首先解決:
for g,s in d.items():
for i in list(s):
s[i] = l.pop()
您還需要在列表為空時停止:
try:
for g,s in d.items():
for i in list(s):
s[i] = l.pop()
except IndexError:
pass
else:
if l:
# There weren't enough slots, handle it or raise an exception
我假設您想將名稱放入dict值中,以替換空字符串。 在這種情況下,我將轉儲您的初始詞典並以這種方式進行操作:
from itertools import count
def generate(lst):
target = {}
for index in count(1):
target[index] = {}
for subindex in xrange(1, 4):
target[index][subindex] = lst.pop()
if not lst:
return target
generate(['Erich Martin', 'Zia Michael', 'Olga Williams', 'Uma Gates'])
或更優雅
from itertools import izip_longest
def generate(lst):
groups = izip_longest(fillvalue='', *([iter(lst)] * 3))
dictgroups = [dict(enumerate(group, 1)) for group in groups]
return dict(enumerate(dictgroups, 1))
generate(['Erich Martin', 'Zia Michael', 'Olga Williams', 'Uma Gates'])
兩種解決方案都可以與任何輸入列表一起使用,並且對長度沒有限制,就像對現有字典進行變異的方法一樣。
一種不同的方法,以處理dict
固有的未分類性質。 另外,從列表中彈出似乎會以相反的順序給出值,並破壞原始列表(如果您不再使用它,可以這樣做),因此我根據需要使用了iter
來遍歷列表。
d = {1 : {1 : '', 2 : '', 3 : ''},2 : {1 : '', 2 : '', 3 : ''}}
l = ['Erich Martin', 'Zia Michael', 'Olga Williams', 'Uma Gates']
i = iter(l)
for outer in sorted(d.keys()):
for inner in sorted(d[outer].keys()):
try:
d[outer][inner]=next(i)
except StopIteration:
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.