简体   繁体   English

在Python中提取嵌套的字典值

[英]Extract nested dictionary values in Python

I think I'm close but spinning in circles on this one. 我想我很亲密,但是在这上面转圈了。 I have a dictionary in Python that has been imported from JSON. 我有一个从JSON导入的Python字典。 The raw data is too much to post here. 原始数据太多,无法在此处发布。 The code works like I want and prints what I want, except it only returns the last value from the dictionary. 该代码的工作方式与我想要的一样,并打印出我想要的内容,只是它仅返回字典中的最后一个值。 How would I modify this to return all values and print exactly how it is shown here? 我将如何修改它以返回所有值并精确打印此处显示的内容? Ultimately I want to take this data and add it to a database as one entry. 最终,我想将这些数据作为一项添加到数据库中。

Code: 码:

text = json.loads(content)

a = {}

def extract(DictIn, Dictout):
    for key, value in DictIn.iteritems():
        if isinstance(value, dict): 
            extract(value, Dictout)
        elif isinstance(value, list):
            for i in value:
                extract(i, Dictout)
        else:
            Dictout[key] = value

extract(text, a)

for k, v in a.iteritems():
    print k, ":", v

Result should look like the following, but have the other 40 or so entries. 结果应如下所示,但还有其他40个左右的条目。 Currently the code only shows the last entry: 当前代码仅显示最后一个条目:

datetime : 2014-06-10T20:00:00-0600
date : 2014-06-10
href : http://xxxxxxxxxxxx.json
lng : -94.5554
id : 17551289
createdAt : 2013-07-30T12:18:56+0100
city : Kansas City, MO, US
billing : headline
totalEntries : 37
type : Concert
billingIndex : 1
status : ok
perPage : 50
setlistsHref : xxxxxxxxxxxx:51b7f46f-6c0f-46f2-9496-08c9ec2624d4/setlists.json
lat : 39.0763
displayName : Ben Folds
eventsHref : http://xxxxxxx.08c9ec2624d4/calendar.json
popularity : 0.0
uri : xxxxxxxxxxxxxxxxxx
mbid : xxxxxxxxxxx
onTourUntil : 2014-06-10
time : 20:00:00
page : 1

The problem is with your Dictout[key] = value 问题出在你的Dictout[key] = value

in Python Dictionary the keys are unique 在Python词典中, keysunique

Assume 假设

_d = {1: 'one', 2: 'two'}

>>> print _d
{1: 'one', 2: 'two'}

>>> _d[1] = 'another one'
>>> print _d
{1: 'another one', 2: 'two'}

I guess in your for loop you are overwriting value of an existing key , that's why only your last entry is getting stored !. 我猜在您的for循环中,您正在overwriting value现有key overwriting value ,这就是为什么仅存储最后一个条目的原因!

Try changing your data structure, something like list of dictionaries , so that your output may look like, 尝试更改数据结构(如list of dictionaries ,以使输出看起来像,

my_out_list = [{1: 'one', 2: 'two'}, {1: 'another one', 2: 'two'}]

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

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