我有一个字典列表如下
[
{
"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"
}
]
答案 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列表