困惑如何从字典列表中提取值

时间:2016-08-23 11:12:56

标签: python python-3.x dictionary

diction_a = {'x': {'zebra':'white', 'raptors':'bosh', 'teams' :  [{'a': 0, 'b': '123456', 'c': 1, 'd': 'xuix'}, {'a': 0, 'b': '234567', 'c': 1, 'd': 'lebron?', 'owner': 'heat'}, {'a': 0, 'b': '7890324', 'c': 1, 'd': 'durant'}, ..{many more with similar format}]

所以我给了diction_a作为字典,但是我需要从列表中的多个字典中提取'团队'中'b'的值。我在下面有这个代码,但是当我打印list_of_b时它是一个空列表。

search = diction_a ['x']['teams']
list_of_b = [a.get('b') for a in search if 'b' in a]

2 个答案:

答案 0 :(得分:0)

print [val['b']  for x in diction_a.values() for val in  x['teams'] ]

输入:

diction_a = {'x': {'zebra':'white', 'raptors':'bosh','teams' :  [{'a': 0, 'b': '123456', 'c': 1, 'd': 'xuix'}, {'a': 0, 'b': '234567', 'c': 1, 'd': 'lebron?', 'owner': 'heat'},{'a': 0, 'b': '7890324', 'c': 1, 'd': 'durant'}] } }

输出:

['123456', '234567', '7890324']

答案 1 :(得分:-1)

您应首先确认您的数据结构是否正确,这是一个使用您的代码的工作示例:

diction_a = {
    'x': {
        'zebra': 'white',
        'raptors': 'bosh',
        'teams':  [
            {
                'a': 0,
                'b': '123456',
                'c': 1,
                'd': 'xuix'
            }, {
                'a': 0,
                'b': '234567',
                'c': 1,
                'd': 'lebron?',
                'owner': 'heat'
            }, {
                'a': 0,
                'b': '7890324',
                'c': 1,
                'd': 'durant'
            }
        ]
    }
}


search = diction_a['x']['teams']
list_of_b = [a.get('b') for a in search if 'b' in a]
print list_of_b
相关问题