繁体   English   中英

在Python中提取嵌套的字典值

[英]Extract nested dictionary values in Python

我想我很亲密,但是在这上面转圈了。 我有一个从JSON导入的Python字典。 原始数据太多,无法在此处发布。 该代码的工作方式与我想要的一样,并打印出我想要的内容,只是它仅返回字典中的最后一个值。 我将如何修改它以返回所有值并精确打印此处显示的内容? 最终,我想将这些数据作为一项添加到数据库中。

码:

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

结果应如下所示,但还有其他40个左右的条目。 当前代码仅显示最后一个条目:

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

问题出在你的Dictout[key] = value

在Python词典中, keysunique

假设

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

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

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

我猜在您的for循环中,您正在overwriting value现有key overwriting value ,这就是为什么仅存储最后一个条目的原因!

尝试更改数据结构(如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