2014-11-06 104 views
1

我有一個值列表和字典的詞典。他們是這個樣子:如何將列表中的值映射到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。

謝謝!

+1

它是如何將列表中的值映射到字典?你能提供一個你想得到什麼的例子嗎? – bgusach 2014-11-06 20:16:12

+1

它看起來像你真的想砍你的名字列表。你可以試試這個:[l [i:i + 3]我在範圍內(0,len(l),3)]。這將創建一個列表,每次分組的項目爲3。 – vikramls 2014-11-06 20:19:49

+0

你知道,那個字典沒有訂單。 – Daniel 2014-11-06 20:21:00

回答

1

試試這個:

編輯的基礎上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: ''}} 
+0

這樣做;我曾嘗試過一些len(l)> 0:沒有成功。這更有意義,更清潔。 – lorsungcu 2014-11-06 20:41:43

+1

在Python中,不需要檢查列表的長度。只要做'如果不是l:打破' – bgusach 2014-11-06 20:54:20

+0

你是對的,@ ikaros45。我已經用你的建議更新了我的答案。 – 2014-11-06 21:11:59

0

您在迭代它時正在修改字典。解決這個問題首先:

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 
0

我假設你想把名字寫入字典值,替換空字符串。在這種情況下,我會傾倒您最初的字典,這樣來做:

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

兩種解決方案都將與任何輸入列表的工作,對長度沒有限制,你將有用改變現有字典的方法。

0

一種不同的方法,以處理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