简体   繁体   English

从词典中的列表创建词典

[英]Creating Dictionaries from Lists inside of Dictionaries

I'm quite new to Python and I have been stumped by a seemingly simple task. 我对Python还是很陌生,但我被一个看似简单的任务所困扰。 In part of my program, I would like to create Secondary Dictionaries from the values inside of lists, of which they are values of a Primary Dictionary. 在我的程序的一部分中,我想从列表内部的值创建辅助字典,这些值是主字典的值。

I would also like to default those values to 0 我也想将这些值默认为0

For the sake of simplicity, the Primary Dictionary looks something like this: 为了简单起见,主要字典看起来像这样:

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

What I would like my result to be is something like: 我希望结果是这样的:

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

I understand the process should be to iterate through each list in the primaryDict, then iterate through the items in the list and then assign them as Dictionaries. 我了解该过程应该是遍历primaryDict中的每个列表,然后遍历列表中的项目,然后将它们分配为Dictionary。

I've tried many variations of "for" loops all looking similar to: 我尝试过许多“ for”循环的变体,它们看起来都类似于:

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

I've also tried some methods of combining Dictionary and List comprehension, but when I try to index and print the Dictionaries with, for example: 我还尝试了一些结合字典和列表理解的方法,但是当我尝试使用以下方法对索引和索引字典进行打印时:

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

I get the "TypeError: list indices must be integers or slices, not str", which I interpret that my 'apple' is not actually a Dictionary, but still a string in a list. 我收到“ TypeError:列表索引必须是整数或切片,而不是str”,我将其解释为“苹果”实际上不是字典,而是列表中的字符串。 I tested that by replacing 'apple' with 0 and it just returns 'apple', proving it true. 我通过将'apple'替换为0进行测试,它仅返回'apple',证明它是正确的。

I would like help with regards to: 我需要以下方面的帮助:

-Whether or not the values in my list are assigned as Dictionaries with value '0' -是否将我列表中的值分配为“ 0”值的“字典”

or 要么

-Whether the mistake is in my indexing (in the loop or the print function), and what I am mistaken with -错误是在我的索引中(在循环中还是在打印功能中),以及我误会了什么

or 要么

-Everything I've done won't get me the desired outcome and I should attempt a different approach -我所做的一切都无法获得理想的结果,我应该尝试其他方法

Thanks 谢谢

Here is a dict comprehension that works: 这是一个有效的字典理解:

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

There are two problems with your current code. 您当前的代码有两个问题。 First, you are trying to iterate over listKey , which is a string. 首先,您尝试遍历listKey ,它是一个字符串。 This produces a sequence of characters. 这将产生一个字符序列。

Second, you should use something like 其次,您应该使用类似

[{word: 0} for word in words]

in place of 代替

{word:0 for word in listKey}

You are close. 你近了 The main issue is the way you iterate your dictionary, and the fact you do not append or assign your sub-dictionaries to any variable. 主要问题是迭代字典的方式,以及您没有将子字典追加或分配给任何变量的事实。

This is one solution using only for loops and list.append . 这是仅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}]}

A more Pythonic solution is to use a single list comprehension. 一种更Python化的解决方案是使用单个列表理解。

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

If you are using your dictionary for counting, which seems to be the implication, an even more Pythonic solution is to use collections.Counter : 如果您正在使用字典进行计数,这似乎是在暗示,那么一个更Python化的解决方案是使用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})}

There are specific benefits attached to collections.Counter relative to normal dictionaries. collections.Counter有一些特殊的好处

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

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

print(primaryDict)

Output: 输出:

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

Hope this helps! 希望这可以帮助!

You can get the data structure that you desire via: 您可以通过以下方式获取所需的数据结构:

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}]}    

But the correct nested access would be: 但是正确的嵌套访问将是:

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

If you actually want primaryDict['list_a']['apple'] to work, do instead 如果您实际上希望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}}

@qqc1037 , I checked and updated your code to make it working. @ qqc1037 ,我检查并更新了您的代码以使其正常运行。 I have mentioned the problem with your code as comments. 我已将您的代码问题作为注释提及。 Finally, I have also added one more example using list comprehension , map() & lambda function . 最后,我还添加了一个使用list comprehensionmap()lambda函数的示例。

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
        }
    ]
}
"""

Another example: Using list comprehension, map(), lambda function 另一个示例:使用列表推导,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
        }
    ]
}
"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM