如何从嵌套字典中获取数据?

时间:2019-05-14 10:39:41

标签: python

我有字典:

 dict1 = {"1111111-1":{"name":"Bill","id":"123"},"2222222-1":{"name":"John","id":"124"}, "3333333-1":{"name":"Ted","id":"125"}, "2222222-2":{"name":"John","id":"126"}}

我只想打印不带键值的名称和ID(“ 1111111-1”,“ 2222222-1”等)。最后,我要列出名称和ID。

6 个答案:

答案 0 :(得分:1)

这种方法怎么样:

list_names = []
for key, value in dict1.items():
    print(value['name'], value['id'])
    list_names.append(value['name'])

print(list_names)

答案 1 :(得分:0)

由于目前尚不清楚输出,因此可以采取以下步骤-

list(dict1.values())

这将显示具有名称和ID的词典列表-

[{'name': 'Bill', 'id': '123'}, {'name': 'John', 'id': '124'}, {'name': 'Ted', 'id': '125'}, {'name': 'John', 'id': '126'}]

答案 2 :(得分:0)

您可以简单地执行以下操作:

print([list(x.values()) for x in dict1.values()])

答案 3 :(得分:0)

我认为您需要:

names = [v['name'] for k,v in dict1.items()]
ids = [v['id'] for k,v in dict1.items()]

答案 4 :(得分:0)

dict1 = {"1111111-1":{"name":"Bill","id":"123"},"2222222-1":{"name":"John","id":"124"}, "3333333-1":{"name":"Ted","id":"125"}, "2222222-2":{"name":"John","id":"126"}}

names=[]
ids=[]

for value in dict1.values():
    names.append(value["name"])
    ids.append(value["id"])

print(names)
print(ids)

答案 5 :(得分:0)

首先制作一个包含名称和ID的字典,然后可以轻松访问所需的列表:

name_id_dict = { v['name'] : v['id'] for k,v in dict1.items() }

names = name_id_dict.keys()
ids = name_id_dict.values()