[英]Extract values from dictionary to list in Python
I have below dictionary in Python, and I would like to extract the value of "red" and apeend it to a list. 我在Python中有下面的字典,我想提取“ red”的值并将其附加到列表中。 I have the dictionary store in the variable "Reference" as per below:
我将字典存储在变量“ Reference”中,如下所示:
Reference = {
u'Message': u'',
u'Code': 0,
u'Data': [{u'Status': u'Running', u'InternalReferenceNumber': u'25333342818', u'Currency': u'EUR', u'red': u'WA-1a9asd4sdfdas, u'PnlInfo': None},
{u'Status': u'Running', u'InternalReferenceNumber': u'25333342818', u'Currency': u'EUR', u'red': u'WA-150824979asd4', u'PnlInfo': None},
{u'Status': u'Running', u'InternalReferenceNumber': u'25333342818', u'Currency': u'EUR', u'red': u'WA-1508249792364', u'PnlInfo': None}]
}
I have tried below code but somehow I do not achieve to get below output (ie a list with the value extracted from the dictionary for the key "red": 我已经尝试过下面的代码,但是以某种方式无法达到下面的输出(即列表,其中从字典中提取了键“ red”的值):
results = [WA-1a9asd4sdfdas,WA-150824979asd4,WA-1508249792364]
Code: 码:
results = [ item['BetPlacementReference'] for item in Reference]
print results
Could you please advise how to get the desired list? 您能否建议如何获得所需的清单?
Thanks. 谢谢。
Try this: 尝试这个:
results = [item['red'] for item in Reference['Data']]
Honestly, I have no clue, why you try to find anthing with a key 'BetPlacementReference'
in your data :) 老实说,我不知道为什么要尝试在您的数据中找到带有键
'BetPlacementReference'
的内容:)
Just do : 做就是了 :
>>> out = []
>>> for ele in Reference['Data']:
out.append(ele['red'])
>>> out
=> ['WA-1a9asd4sdfdas', 'WA-150824979asd4', 'WA-1508249792364']
Or, a single liner using List comprehension
: 或者,使用
List comprehension
的单个班轮:
>>> [ ele['red'] for ele in Reference['Data'] ]
=> ['WA-1a9asd4sdfdas', 'WA-150824979asd4', 'WA-1508249792364']
What you could use to get the value of red for a certain point in data where 0 is the dictionary within the list: 您可以用来获取数据中某一点的红色值的方法,其中0是列表中的字典:
Reference['Data'][0]['red']
This works because Data is subscriptable and so is each dictionary within the list. 之所以可行,是因为Data是可以下标的,列表中的每个字典也可以下标。 To make it loop for every value we need to do:
为了使它循环为每个值,我们需要做的是:
red_list = []
for ref_dict in Reference['Data']:
red_list.append(ref_dict['red'])
This will go through every part of Data
in Reference
adding the value of red to red_list
. 这将遍历
Reference
中Data
每个部分,并将red的值添加到red_list
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.