从字典中的列表创建字典

Creating Dictionaries from Lists inside of Dictionaries

我是 Python 的新手,我被一个看似简单的任务难住了。 在我的程序的一部分中,我想从列表中的值创建二级词典,它们是一级词典的值。

我还想将这些值默认为 0

为了简单起见,初级词典看起来像这样:

primaryDict = {'list_a':['apple', 'orange'], 'list_b':['car', 'bus']}

我希望我的结果是这样的:

{'list_a':[{'apple':0}, {'orange':0}], 'list_b':[{'car':0}, {'bus':0}]}

我理解这个过程应该是遍历 primaryDict 中的每个列表,然后遍历列表中的项目,然后将它们分配为字典。

我尝试了很多 "for" 循环的变体,看起来都类似于:

for listKey in primaryDict:
    for word in listKey:
        {word:0 for word in listKey}

我也尝试过一些结合字典和列表理解的方法, 但是当我尝试索引和打印字典时,例如:

print(primaryDict['list_a']['apple'])

我得到 "TypeError: list indices must be integers or slices, not str",我将其解释为我的 'apple' 实际上不是字典,而是列表中的一个字符串。我通过用 0 替换 'apple' 来测试它,它只是 returns 'apple',证明它是正确的。

我需要以下方面的帮助:

-我列表中的值是否被分配为值为“0”的字典

-错误是否在我的索引中(在循环或打印函数中),以及我弄错了什么

-我所做的一切都不会得到我想要的结果,我应该尝试不同的方法

谢谢

primaryDict = {'list_a':['apple', 'orange'], 'list_b':['car', 'bus']}

for listKey  in primaryDict:
    primaryDict[i] = [{word:0} for word in primaryDict[listKey]]

print(primaryDict)

输出:

{'list_a':[{'apple':0}, {'orange':0}], 'list_b':[{'car':0}, {'bus':0}]}

希望对您有所帮助!

您可以通过以下方式获取您想要的数据结构:

primaryDict = {'list_a':['apple', 'orange'], 'list_b':['car', 'bus']}
for k, v in primaryDict.items():
    primaryDict[k] = [{e: 0} for e in v]

# primaryDict
{'list_b': [{'car': 0}, {'bus': 0}], 'list_a': [{'apple': 0}, {'orange': 0}]}    

但正确的嵌套访问应该是:

print(primaryDict['list_a'][0]['apple'])  # note the 0

如果您确实希望 primaryDict['list_a']['apple'] 工作,请改为

for k, v in primaryDict.items():
    primaryDict[k] = {e: 0 for e in v}

# primaryDict
{'list_b': {'car': 0, 'bus': 0}, 'list_a': {'orange': 0, 'apple': 0}}

这是一个有效的字典理解:

{k: [{v: 0} for v in vs] for k, vs in primaryDict.items()}

您当前的代码有两个问题。首先,您尝试迭代 listKey,这是一个字符串。这会产生一个字符序列。

其次,您应该使用

[{word: 0} for word in words]

代替

{word:0 for word in listKey}

你很接近。主要问题是您迭代字典的方式,以及您没有将子字典附加或分配给任何变量的事实。

这是一个仅使用 for 循环和 list.append 的解决方案。

d = {}
for k, v in primaryDict.items():
    d[k] = []
    for w in v:
        d[k].append({w: 0})

{'list_a': [{'apple': 0}, {'orange': 0}],
 'list_b': [{'car': 0}, {'bus': 0}]}

一个更 Pythonic 的解决方案是使用单个列表理解。

d = {k: [{w: 0} for w in v] for k, v in primaryDict.items()}

如果你正在使用你的字典来计数,这似乎是暗示,一个更 Pythonic 的解决方案是使用 collections.Counter:

from collections import Counter

d = {k: Counter(dict.fromkeys(v, 0)) for k, v in primaryDict.items()}

{'list_a': Counter({'apple': 0, 'orange': 0}),
 'list_b': Counter({'bus': 0, 'car': 0})}

相对于普通词典,collections.Counter附有specific benefits

@qqc1037,我检查并更新了您的代码以使其正常工作。我已经在评论中提到了您的代码的问题。最后,我还添加了一个使用 list comprehensionmap() & lambda function 的示例。

import json 

secondaryDict = {}

for listKey in primaryDict:
    new_list = [] # You did not define any temporary list
    for word in primaryDict [listKey]: # You forgot to use key that refers the list
        new_list.append( {word:0}) # Here you forgot to append to list
    secondaryDict2.update({listKey: new_list}) # Finally, you forgot to update the secondary dictionary

# Pretty printing dictionary
print(json.dumps(secondaryDict, indent=4));

"""
{
    "list_a": [
        {
            "apple": 0
        },
        {
            "orange": 0
        }
    ],
    "list_b": [
        {
            "car": 0
        },
        {
            "bus": 0
        }
    ]
}
"""

另一个例子:使用列表理解、map()、lambda函数

# Using Python 3.5.2
import json

primaryDict = {'list_a':['apple', 'orange'], 'list_b':['car', 'bus']}

secondaryDict = dict(map(lambda key: (key, [{item:0} for item in primaryDict[key]]), list(primaryDict) ))

# Pretty printing secondary dictionary
print(json.dumps(secondaryDict, indent=4))

"""
{
    "list_a": [
        {
            "apple": 0
        },
        {
            "orange": 0
        }
    ],
    "list_b": [
        {
            "car": 0
        },
        {
            "bus": 0
        }
    ]
}
"""