#python #dictionary
#python #словарь
Вопрос:
Ниже у меня есть список словарей:
dict = [{'name': 'Sector',
'entity': 'ORG(100.0)',
'synonyms': "Sector:['sector', 'sphere'], , ",
'definition': 'Sector'},
{'name': 'Community Name',
'entity': 'PERSON(39.74)',
'synonyms': "Community:['biotic_community', 'community', 'community_of_interests', 'residential_area', 'residential_district']",
'definition': 'Community'}]
Как мне добавить новый ключ, который группирует сущность и определение в качестве значений?
желаемый результат (категория — это новый добавленный ключ):
dict = [{'name': 'Sector',
'category': {
'entity': 'ORG(100.0)',
'definition': 'Sector'},
'synonyms': "Sector:['sector', 'sphere'], , "},
{'name': 'Community Name',
'category':{
'entity': 'PERSON(39.74)',
'definition': 'Community'},
'synonyms': "Community:['biotic_community', 'community', 'community_of_interests', 'residential_area', 'residential_district']"}]
Я пробовал [{'name': i.pop('name'), 'category': i} for I in dict]
, но это работает только для ключей, расположенных в последовательном порядке, как я могу изменить это, чтобы я мог выбирать определенные ключи, поскольку entity
и definition
не находятся рядом друг с другом?
Комментарии:
1. предполагается ли только добавить
category
ключ и иметь ключи(entitiy, definition, synonyms)
внутри него?2. Да, но это только для сущности и определения, а не синонимов.
Ответ №1:
Похоже, вам нужно
data = [{'name': 'Sector',
'entity': 'ORG(100.0)',
'synonyms': "Sector:['sector', 'sphere'], , ",
'definition': 'Sector'},
{'name': 'Community Name',
'entity': 'PERSON(39.74)',
'synonyms': "Community:['biotic_community', 'community', 'community_of_interests', 'residential_area', 'residential_district']",
'definition': 'Community'}]
subkeys = ['entity', 'definition']
result = [{'category': {k: i.pop(k) for k in subkeys}, **i} for i in data]
print(result)
Вывод:
[{'category': {'definition': 'Sector', 'entity': 'ORG(100.0)'},
'name': 'Sector',
'synonyms': "Sector:['sector', 'sphere'], , "},
{'category': {'definition': 'Community', 'entity': 'PERSON(39.74)'},
'name': 'Community Name',
'synonyms': "Community:['biotic_community', 'community', "
"'community_of_interests', 'residential_area', "
"'residential_district']"}]
Комментарии:
1. Спасибо за быстрый ответ и отличное решение. Мне интересно, есть ли способ изменить порядок ключей? Поскольку после функции клавиша категории находится вверху.
2. Да, вы можете .. в stackoverflow есть несколько вопросов с ответами на это. Это довольно распространенный вопрос 🙂
Ответ №2:
Похоже, вы хотите преобразовать каждый объект, и в этом случае я бы выбрал map с пользовательской функцией.
import json
dicts = [
{
'name': 'Sector',
'entity': 'ORG(100.0)',
'synonyms': "Sector:['sector', 'sphere'], , ",
'definition': 'Sector'
},
{
'name': 'Community Name',
'entity': 'PERSON(39.74)',
'synonyms': "Community:['biotic_community', 'community', 'community_of_interests', 'residential_area', 'residential_district']",
'definition': 'Community'
}
]
def map_func(item):
item['category'] = {'entity': item['entity'], 'definition': item['definition']}
item.pop('entity')
item.pop('definition')
return item
mapped_dicts = map(lambda x: map_func(x), dicts)
print(json.dumps(list(mapped_dicts), indent=2))
[
{
"name": "Sector",
"synonyms": "Sector:['sector', 'sphere'], , ",
"category": {
"entity": "ORG(100.0)",
"definition": "Sector"
}
},
{
"name": "Community Name",
"synonyms": "Community:['biotic_community', 'community', 'community_of_interests', 'residential_area', 'residential_district']",
"category": {
"entity": "PERSON(39.74)",
"definition": "Community"
}
}
]