简体   繁体   English

在 Python 中结合列表和字典

[英]Combining List and dictionary in Python

I have a list with a dictionary in it with a list in it like this:我有一个带有字典的列表,其中有一个列表,如下所示:

a = [{'name': ['item1', 'item2']}]

And I need to get that result like this:我需要得到这样的结果:

[
    {
        'name': 'item1',
        'name': 'item2'
    }
]

So for your problem, First your idea is wrong as in a dictionary in python you cannot have same key more than ones as you reference the data with the keys and if duplicate exists then there will be problem.因此,对于您的问题,首先您的想法是错误的,因为在 python 中的字典中,当您使用密钥引用数据时,您不能拥有多个相同的密钥,如果存在重复,则会出现问题。

So the solution could be:所以解决方案可能是:

[
    {
        'name0': 'item1',
        'name2': 'item2'
    }
]

For this you have to iterate through all the elements in the innermost list and create a new dictionary within a list as expected in the desired result and then add elements one by one in the inner dictionary with keys like name1, name2, ...为此,您必须遍历最内层列表中的所有元素,并按照所需结果在列表中创建一个新字典,然后在内部字典中一个一个地添加元素,其中包含 name1、name2、...

I am not sure about your requirement, I would suggest you to go through the documentation here我不确定您的要求,我建议您通过此处的文档 go

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).最好将字典视为一组键:值对,并要求键是唯一的(在一个字典中)。

So, as of your desired output of a dictionary with 2 same keys is not possible.因此,从您想要的 output 开始,不可能有 2 个相同键的字典。

But you may try something like this但你可以尝试这样的事情

a=[{'name': ['item1', 'item2']}]

result_list=[]

for item in a[0]['name']:
    result_list.append({'name':item})

print(result_list)

Output Output

[{'name': 'item1'}, {'name': 'item2'}]

This appears to be something similar to your requirement.这似乎与您的要求相似。 You can use list index to access the individual dictionaries.您可以使用列表索引来访问各个字典。

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

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