从python中的列表中删除重复并合并内部字典项

时间:2017-05-18 07:53:54

标签: python json python-2.7 list dictionary

我有一个字典列表如下

[
{
    "user": [
        "jon"
    ], 
    "email": "jon123@email.com"
}, 
{
    "user": [
        "mike"
    ], 
    "email": "mike456@email.com"
}, 
{
    "user": [
        "J Jon", 
        "Jonathan"
    ], 
    "email": "jon123@email.com"
}, 
{
    "user": [
        "taylor"
    ], 
    "email": "taylor789@email.com"
}, 
{
    "user": [
        "me_mike"
    ], 
    "email": "mike456@email.com"
}
]

我想合并两个列表项(作为字典),如果这两个项看起来在字典内的email列表中具有相同的user但不同的值。如何从python中的上面显示的列表中获得如下结果。

[
{
    "user": [
        "jon",
        "J Jon", 
        "Jonathan"
    ], 
    "email": "jon123@email.com"
}, 
{
    "user": [
        "mike",
        "me_mike"
    ], 
    "email": "mike456@email.com"
},  
{
    "user": [
        "taylor"
    ], 
    "email": "taylor789@email.com"
}     
]

2 个答案:

答案 0 :(得分:4)

试试这个 -

a = ... # the json list
d = {}
for i in a:
    d.setdefault(i['email'], []).extend(i['user'])

print [{'user' : v, 'email' : k} for k, v in d.items()]

答案 1 :(得分:0)

for dictionary in my_list:
    actual_email = dictionary.get('email')
    for dictionary_search in my_list:
        if dictionary != dictionary_search and actual_email == dictionary_search.get('email'):
            users = dictionary_search.get('user')
            for user in users:
                dictionary.get('user', []).append(user)
            my_list.remove(dictionary_search)
print(my_list)

my_list是你的json列表