如何解析这个JSON dict来打印出一个键值对?

时间:2017-04-27 14:11:27

标签: python json dictionary

cow = {
    "data": [
        {
            "id": "1179640025492630",
            "indicator": "google-analytics|UA-97996598-1",
            "type": "API_KEY"
        },
        {
            "id": "1469013519830038",
            "indicator": "google-analytics|UA-96613605-2",
            "type": "API_KEY"
        },
        {
            "id": "1459958767410551",
            "indicator": "google-analytics|UA-86399386-2",
            "type": "API_KEY"
        },
        {
            "id": "1507839102569000",
            "indicator": "google-analytics|UA-89570367-2",
            "type": "API_KEY"
        },
        {
            "id": "1276736575767341",
            "indicator": "google-analytics|UA-69774312-4",
            "type": "API_KEY"
        },
        {
            "id": "1292251910882451",
            "indicator": "google-analytics|UA-93952538-3",
            "type": "API_KEY"
        }
    ],
    "paging": {
        "cursors": {
            "after": "NQZDZD",
            "before": "MAZDZD"
        }
    }
}

我想从数据字典中提取“id”:“1179640025492630”。

我试过使用for循环,如:

for i in cow['data']:
    for key,value in i:
        if(i == 'id'):
            print key,value
        else:
            pass

它给我一个值错误,如:

Traceback (most recent call last):
  File "./dict.py", line 14, in <module>
    for key,value  in ['data']:
  ValueError: too many values to unpack

如果我使用.iteritems,我会收到AttributeError

Traceback (most recent call last):
  File "./dict.py", line 14, in <module>
    for key,value   in ['data'].iteritems:
  AttributeError: 'list' object has no attribute 'iteritems'

4 个答案:

答案 0 :(得分:0)

如果你想要一个使用嵌套for循环的更干净的解决方案,你可以使用python的map函数迭代data中的所有字典,只取id }值。

>>> list(map(lambda d: 'id: {}'.format(d['id']), cow['data']))
['id: 1179640025492630', 'id: 1469013519830038', 'id: 1459958767410551', 'id: 1507839102569000', 'id: 1276736575767341', 'id: 1292251910882451']

答案 1 :(得分:0)

如果要提取 id 字段,请使用映射函数:

map(lambda item: ("id", item["id"]), cow["data"])

并且您将获得一个元组列表(请注意,py3地图是懒惰的,您将强制评估列表)。

答案 2 :(得分:0)

或者你可以结合listdictionary理解,这可能更容易处理。

result = [{k:v for k,v in dikt.items() if k == "id"} for dikt in cow['data']]

给你

  

[{'id':'1179640025492630'},{'id':'1469013519830038'},{'id':'1459958767410551'},{'id':'1507839102569000'},{'id':' 1276736575767341'},{'id':'1292251910882451'}]

你可以这样打印出来:

print "\n".join([i['id'] for i in result])

答案 3 :(得分:0)

如果您只想打印与id s相关联的所有值:

for thing in cow["data"]:
    print(thing["id"])

输出:

1179640025492630
1469013519830038
1459958767410551
1507839102569000
1276736575767341
1292251910882451