如何在Python中将值从列表映射到嵌套字典?

2024-04-28 16:02:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个值列表和一本字典。它们看起来像这样:

d = {1 : {1 : '', 2 : '', 3 : ''},2 : {1 : '', 2 : '', 3 : ''}}
l = ['Erich Martin', 'Zia Michael', 'Olga Williams', 'Uma Gates']

我正在尝试将列表中的值映射到字典中,在进入下一个嵌套字典之前填充每个字典。最后一本字典会有一些空槽,这很好。我似乎不知道我需要做什么;我跑到列表的末尾,得到了一个keyerror,因为没有更多的值了。以下是我目前掌握的要点:

for g,s in d.items():
        for i in s:
                s[i] = l.pop()

使用python3.4。你知道吗

谢谢!你知道吗


Tags: in列表for字典martinkeyerror末尾michael
3条回答

试试这个:

根据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进行变异一样

相关问题 更多 >