从python3中的嵌套字典列表中打印项目

时间:2018-09-20 14:46:04

标签: python dictionary nested

我有下面这样的数据,如何找到Kevin3和Jeremy在Python3中拥有的tool_id。所以我想要像这样的结果:

4734238, 38374
4734233, 38374

以下是列表:

assignment = [
{
    'id': 4734238,
    'name': 'kevin',
    'tool': {
        'tool_id': '38374',
        'new_tab': False,
        'resource_link_id': '179fd40f91a5b'
    }
},
{
    'id': 4734233,
    'name': 'jeremy',
    'tool': {
        'tool_id': '38374',
        'new_tab': False,
        'resource_link_id': '179fd40f91a5b'
    },
},
{
    'id': 4743233,
    'name': 'Sharon',
}
]

5 个答案:

答案 0 :(得分:2)

assignment = [
{ 'id': "1001",'name': "kevin", 'tool': {'tool_id': '38374'}},
{ 'id': "1002", 'name': "jeremy", 'tool': {'tool_id': '38378'}}
]

findThis = ['kevin', 'jeremy']

for each in assignment:
    if each.get('name') in findThis:
        t = each.get('tool')
        print(each.get('id'), t.get('tool_id'))

我希望它更容易理解。

答案 1 :(得分:1)

这应该做到:

[[i.get('id'), i.get('tool').get('tool_id')] for i in assignment if i.get('name') in ['kevin','jeremy']]

对于此示例,返回:

[[4734238, '38374'], [4734233, '38374']]

答案 2 :(得分:0)

assignment = [
         {
         'id': 4734238,
         'name': "kevin",
         'tool': {
             'tool_id': '38374',
             'new_tab': False,
             'resource_link_id': '179fd40f91a5b'
             }
         },        
         {
         'id': 4734233,
         'name': "jeremy",
         'tool': {
             'tool_id': '38374',
             'new_tab': False,
             'resource_link_id': '179fd40f91a5b'
             }
         },
         {
         'id': 4743233,
         'name': "Sharon"
         }
 ]

In [1]: [item["tool"]["tool_id"] for item in assignment if item["name"] in ["kevin", "jeremy"]]
Out[1]: ['38374', '38374']

答案 3 :(得分:0)

只需遵循到达目的地的路径,看看需要满足哪些条件

for i in assignment:
    if i['name'] == 'kevin' or i['name'] == 'jeremy':
        print("{}, {}".format(i['id'], i['tool']['tool_id']))
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 finder.py 
4734238, 38374
4734233, 38374

答案 4 :(得分:0)

这将为拥有idstool_ids的人提供所有

l = [(person['id'], person['tool']['tool_id']) for person in assignment 
        if 'id' in person and 'tool' in person and 'tool_id' in person['tool']]

for pair in l:
    print(*pair, sep=', ')

打印

4734238, 38374
4734233, 38374