获取Json字典/列表值python

时间:2016-01-22 03:48:20

标签: python json dictionary

我有一个带字典的json文件,并在该字典中列出

{"Dogs": [["spot"], 1], "Cats": [["whiskers"], 1], "fish": [["bubbles", "lefty", "tank", "goldie"], 4], "elephant": [["tiny", "spring"], 2], "zebra": [[], 1], "gazelle": [["red", "blue", "green", "yellow", "gold", "silver"], 6]}

字典中还有更多内容,但从这个例子中你可以看到格式。

with open('myfile.json', 'r') as myfile:
json_data = json.load(myfile)
for e,([v], z) in json_data.items():
  print e, v, z

这给了我一个

too many values to unpack error.

我希望输出看起来像

dogs spot 1
cats whiskers 1

2 个答案:

答案 0 :(得分:1)

假设您想要所有动物名称(?)输出

...
for e, (v, z) in json_data.items():
    print('%s %s %d' % (e.lower(), ' '.join(v), z))

输出

gazelle red blue green yellow gold silver 6
fish bubbles lefty tank goldie 4
cats whiskers 1
zebra  1
elephant tiny spring 2
dogs spot 1

答案 1 :(得分:0)

更简单,因为值始终是一个列表:

gazelle red blue green yellow gold silver 6
fish bubbles lefty tank goldie 4
Cats whiskers 1
zebra  1
elephant tiny spring 2
Dogs spot 1

这给出了:

struct _TREEITEM;
typedef struct _TREEITEM *HTREEITEM;