简体   繁体   English

在字典python中循环

[英]loop inside a dictionary python

I am just starting learning Django and Python... It's been 2 months. 我刚刚开始学习Django和Python……已经两个月了。 I'm doing one of my own personal projects and i have a section where i am querying a webservice and passing back the result to the templates. 我正在做自己的个人项目之一,我在其中一节中查询网络服务并将结果传递回模板。

The webservice is returning a dictionary like below. Web服务正在返回如下字典。

x =  {'ID':[{
    'key-1': 'First Name',
    'key-2': 'John'
},{
    'key-1': 'Last Name',
    'key-2': 'Doe'
},{
    'key-1': 'Age',
    'key-2': '25'
}]

I am expecting to iterate the list inside the dictionary and create my own dictionary like the below: 我期望对字典中的列表进行迭代,并创建自己的字典,如下所示:

d = {'First Name': 'John', 'Last Name': 'Doe', 'Age': '25' }

I am not sure what am i missing, can someone please help me with learning how to build my dictionary? 我不确定我缺少什么,有人可以帮助我学习如何构建字典吗?

Try a dict comprehension and build a new dictionary with key-1 as the key and key-2` as the value. 尝试dict理解并用key-1 as the key and key-2`作为值构建一个新字典。

x = {'ID':[{
    'key-1': 'First Name',
    'key-2': 'John'
},{
    'key-1': 'Last Name',
    'key-2': 'Doe'
},{
    'key-1': 'Age',
    'key-2': '25'
}]}


print({el['key-1']: el['key-2'] for el in x['ID']})

Result 结果

{'Age': '25', 'First Name': 'John', 'Last Name': 'Doe'} {“年龄”:“ 25”,“名字”:“约翰”,“姓氏”:“母鹿”}

Caveat be aware of ordering rules for values method for dictionaries. 警告:请注意字典的values排序方法。

Ordering rules 2.x documentation and 3.x documentation . 订购规则2.x文档3.x文档

EDIT2: EDIT2:

To prevent any weirdness with dictionary ordering and the provided solution, wrap your data into an OrderedDict : 为了避免字典排序和提供的解决方案引起任何怪异,请将数据包装到OrderedDict中

from collections import OrderedDict

x = {'ID':[OrderedDict({
         'key-1': 'First Name',
         'key-2': 'John'
         }),OrderedDict({
         'key-1': 'Last Name',
         'key-2': 'Doe'
         }),OrderedDict({
         'key-1': 'Age',
         'key-2': '25'
        })]}

dict() is a nice option for something like this: dict()是类似这样的不错的选择:

d = dict(each.values() for each in x['ID'])

output: 输出:

{'Age': '25', 'First Name': 'John', 'Last Name': 'Doe'}

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

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