从词典

时间:2017-10-04 10:09:36

标签: python

重新编辑以使其更加清晰简洁

以下数据

[
{
    "name": "name1",
    "a_id": "12345",
    "b_id": "0d687c94c5f4"
},
{
    "name": "name2",
    "a_id": "67890",
    "b_id": "0d687c94c5f4"
},
{
    "name": "name3",
    "a_id": "23857",
    "b_id": "9ec34be3d535"
},
{
    "name": "name4",
    "a_id": "84596",
    "b_id": "9ec34be3d535"
},
{
    "name": "name5",
    "a_id": "d82ebe9815cc",
    "b_id": null
}
]

如何获得

基于“b_id”“0d687c94c5f4”:

id1 = 12345
id2 = 67890

基于“b_id”“9ec34be3d535”:

id3 = 23857
id4 = 84596

3 个答案:

答案 0 :(得分:2)

result = collections.defaultdict(list)

for res in response:
    result[res['b_id']].append(res['a_id'])
  

结果:

defaultdict(list,
            {'0d687c94c5f4': ['12345', '67890'],
             '9ec34be3d535': ['23857', '84596'],
             None: ['d82ebe9815cc']})

答案 1 :(得分:1)

result = {
    item['b_id']: [
        subitem['a_id']
        for subitem in response
        if subitem['b_id'] == item['b_id']
    ]
    for item in response
}

print(result)

>>> {'9ec34be3d535': ['23857', '84596'], '0d687c94c5f4': ['12345', '67890'], None: ['d82ebe9815cc']}

答案 2 :(得分:1)

您的请求不是很清楚..但我认为您的意思是您希望使用不同的密钥重新组合json列表...您可以使用itertools

试试这个:

import itertools
for key, group in itertools.groupby(r, lambda item: item['b_id']):
       print 'b_id', key, [x['a_id'] for x in group]

b_id 0d687c94c5f4 ['12345', '67890']
b_id 9ec34be3d535 ['23857', '84596']
b_id None ['d82ebe9815cc']

或以字典形式

for key, group in itertools.groupby(r, lambda item: item['b_id']):
    print {key: [x['a_id'] for x in group]}

{'0d687c94c5f4': ['12345', '67890']}
{'9ec34be3d535': ['23857', '84596']}
{None: ['d82ebe9815cc']}