【发布时间】:2020-05-03 14:46:18
【问题描述】:
我需要根据字典列表中的对象合并一些字典的帮助。这可能吗?
我的数据:
mongo_data = [{
'url': 'https://goodreads.com/',
'variables': [{'key': 'Harry Potter', 'value': '10.0'},
{'key': 'Discovery of Witches', 'value': '8.5'},],
'vendor': 'Fantasy'
},{
'url': 'https://goodreads.com/',
'variables': [{'key': 'Hunger Games', 'value': '10.0'},
{'key': 'Maze Runner', 'value': '5.5'},],
'vendor': 'Dystopia'
},{
'url': 'https://kindle.com/',
'variables': [{'key': 'Twilight', 'value': '5.9'},
{'key': 'Lord of the Rings', 'value': '9.0'},],
'vendor': 'Fantasy'
},{
'url': 'https://kindle.com/',
'variables': [{'key': 'The Handmaids Tale', 'value': '10.0'},
{'key': 'Divergent', 'value': '9.0'},],
'vendor': 'Fantasy'
}]
我的代码:
我使用 [groupby] 将具有相同 URL 的项目组合在一起。
from itertools import groupby, chain
import json
searches = []
for key, group in groupby(mongo_data, key=lambda chunk: chunk['url']):
search = {}
search["url"] = key
search["results"] = [{"genre": result["vendor"], "data": result["variables"]} for result in group]
searches.append(search)
print(json.dumps(searches))
我的输出
[
{
"url": "https://goodreads.com/",
"results": [
{
"genre": "Fantasy",
"data": [
{
"key": "Harry Potter",
"value": "10.0"
},
{
"key": "Discovery of Witches",
"value": "8.5"
}
]
},
{
"genre": "Dystopia",
"data": [
{
"key": "Hunger Games",
"value": "10.0"
},
{
"key": "Maze Runner",
"value": "5.5"
}
]
}
]
},
{
"url": "https://kindle.com/",
"results": [
{
"genre": "Fantasy",
"data": [
{
"key": "Twilight",
"value": "5.9"
},
{
"key": "Lord of the Rings",
"value": "9.0"
}
]
},
{
"genre": "Fantasy",
"data": [
{
"key": "The Handmaids Tale",
"value": "10.0"
},
{
"key": "Divergent",
"value": "9.0"
}
]
}
]
}
]
正如您在https://kindle.com/ 下看到的那样,我有两次"genre":"Fantasy"。而不是打印两次。我可以在没有重复的情况下合并它们吗?
所以我希望我的预期结果是:
{
"url": "https://kindle.com/",
"results": [
{
"genre": "Fantasy",
"data": [
{
"key": "Twilight",
"value": "5.9"
},
{
"key": "Lord of the Rings",
"value": "9.0"
},
{
"key": "The Handmaids Tale",
"value": "10.0"
},
{
"key": "Divergent",
"value": "9.0"
}
]
}
]
}
]
这可能吗?
【问题讨论】:
标签: python python-3.x dictionary object arraylist