【问题标题】:Extract nested dictionary values in Python在 Python 中提取嵌套字典值
【发布时间】:2013-08-09 12:07:31
【问题描述】:

我想我已经很接近了,但在这个问题上绕圈子。我有一个从 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

【问题讨论】:

  • 如果JSON中的数组中有数组会怎样?或者如果顶层是一个数组?
  • 我建议查看 json 本身,您很有可能会覆盖 DictOut 中的键。这是因为 dict/list json 树的“叶子”具有相同的键名,因此当您“展平”该叶子时,您将覆盖之前具有相同键的展平叶子。因此,您似乎只获得了一个条目,因为您已经覆盖了所有其他条目。

标签: python dictionary iterator nested


【解决方案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 循环中你是现有 keyoverwriting value,这就是为什么只有你的最后一个条目被存储!。

尝试改变你的数据结构,比如list of dictionaries,这样你的输出可能看起来像,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    相关资源
    最近更新 更多