如何保存dict的特定部分



我有一个列表,看起来像这个

for i in negocio:   
params = {
'term': i,
'fields': 'title',
'exact_match': 'true'}
response = client.deals.search_deals(params=params)
deal_id.append(response)

deal_id

deal_id运行后,我会收到这些列表。

[{'success': True,
'data': {'items': [{'result_score': 1.28568,
'item': {'id': 151897,
'type': 'deal',
'title': 'deal_1',
'value': None,
'status': 'open',
'visible_to': 7,
'owner': {'id': 13863990},

'person': {'id': 209102,

'organization': None,
'custom_fields': [],
'notes': []}}]},
'additional_data': {'pagination': {'start': 0,
'limit': 100,
'more_items_in_collection': False}}},
{'success': True,
'data': {'items': [{'result_score': 1.28568,
'item': {'id': 151898,
'type': 'deal',
'title': 'deal_2',
'value': None,
'status': 'open',
'visible_to': 7,
'owner': {'id': 13863990},

'person': {'id': 331122,
'organization': None,
'custom_fields': [],
'notes': []}}]},
'additional_data': {'pagination': {'start': 0,
'limit': 100,
'more_items_in_collection': False}}}]

我如何才能只保留列表'item': {'id': 151897}'item': {'id': 151898}中的数字

我看了类似的主题,但没有找到一个可以帮助我的anwser

您应该检查deal_id。它给了我错误,所以我手动修复了它。

my_list = [
{
"success": True,
"data": {
"items": [
{
"result_score": 1.28568,
"item": {
"id": 151897,
"type": "deal",
"title": "deal_1",
"value": None,
"status": "open",
"visible_to": 7,
"owner": {"id": 13863990},
"person": {
"id": 209102,
"organization": None,
"custom_fields": [],
"notes": [],
},
},
}
] # probably the problem is here
},
"additional_data": {
"pagination": {"start": 0, "limit": 100, "more_items_in_collection": False}
},
},
{
"success": True,
"data": {
"items": [
{
"result_score": 1.28568,
"item": {
"id": 151898,
"type": "deal",
"title": "deal_2",
"value": None,
"status": "open",
"visible_to": 7,
"owner": {"id": 13863990},
"person": {
"id": 331122,
"organization": None,
"custom_fields": [],
"notes": [],
},
},
}
]
},
"additional_data": {
"pagination": {"start": 0, "limit": 100, "more_items_in_collection": False}
},
},
]

如果你想删除不需要的密钥,你应该检查每个循环内部并删除它们。否则,您可以保存所需的值,如下所示。

id_item = []
for d in my_list:
for k, v in d.items():
if isinstance(v, dict):
for k, vl in v.items():
# maybe you need more loop iof there are more than one [item {...}]
if vl and isinstance(vl, list):
temp = {"item": {"id": vl[0].get("item").get("id")}}
id_item.append(temp)
print(id_item)
# [{'item': {'id': 151897}}, {'item': {'id': 151898}}]

将此信息保存在变量中:

x = mylist[0]['key name']

然后你可以用删除该密钥

my_list[0]['key name']

并添加一个新的。或者在没有该密钥的情况下生成相同的dict。检查此POST

最新更新