Python 3.x 如何删除字典中的项目?
我正在尝试使用del方法从字典中删除一项(“日志”) 这是我的代码:Python 3.x 如何删除字典中的项目?,python-3.x,Python 3.x,我正在尝试使用del方法从字典中删除一项(“日志”) 这是我的代码: del response.json() ["logs"] print(response.json()) 这是我的JSON字典: {'count': 19804, 'next': {'limit': 1, 'offset': 1}, 'previous': None, 'results': [{'id': '334455', 'custom_id': '112', 'compan
del response.json() ["logs"]
print(response.json())
这是我的JSON字典:
{'count': 19804,
'next': {'limit': 1, 'offset': 1},
'previous': None,
'results':
[{'id': '334455',
'custom_id': '112',
'company': 28,
'company_name': 'Sunshine and Flowers',
'delivery_address': '34 olive beach house, #01-22, 612345',
'delivery_timeslot': {'lower': '2019-12-06T10:00:00Z', 'upper': '2019-12-06T13:00:00Z', 'bounds': '[)'},
'sender_name': 'Edward Shine',
'sender_email': '',
'sender_contact': '91234567',
'removed': None,
'recipient_name': 'Mint Shine',
'recipient_contact': '91234567',
'notes': '',
'items': [{'id': 21668, 'name': 'Loose hair flowers', 'quantity': 1, 'metadata': {}, 'removed': None}, {'id': 21667, 'name': "Groom's Boutonniere", 'quantity': 1, 'metadata': {}, 'removed': None}, {'id': 21666, 'name': 'Bridal Bouquet', 'quantity': 1, 'metadata': {}, 'removed': None}],
'latitude': '1.28283838383642000000',
'longitude': '103.2828037266201000000',
'created': '2019-08-15T05:40:30.385467Z',
'updated': '2019-08-15T05:41:27.930110Z',
'status': 'pending',
'verbose_status': 'Pending',
'**logs**': [{'id': 334455, 'order': '50c402d8-7c76-45b5-b883-e2fb887a507e', 'order_custom_id': '112', 'order_delivery_address': '34 olive beach house, #01-22, 6123458', 'order_delivery_timeslot': {'lower': '2019-12-06T10:00:00Z', 'upper': '2019-12-06T13:00:00Z', 'bounds': '[)'}, 'message': 'Order was created.', 'failure_reason': None, 'success_code': None, 'success_description': None, 'created': '2019-08-15T05:40:30.431790Z', 'removed': None}, {'id': 334455, 'order': '50c402d8-7c76-45b5-b883-e2fb887a507e', 'order_custom_id': '112', 'order_delivery_address': '34 olive beach house, #01-22, 612345', 'order_delivery_timeslot': {'lower': '2019-12-06T10:00:00Z', 'upper': '2019-12-06T13:00:00Z', 'bounds': '[)'}, 'message': 'Order is pending.', 'failure_reason': None, 'success_code': None, 'success_description': None, 'created': '2019-08-15T05:40:30.433139Z', 'removed': None}],
'reschedule_requests': [],
'signature': None}]
但它说的是这个错误
KeyError: 'logs'
我做错了什么?每次调用
response.json()
,它都会返回一个新的dict,因此您从response.json()
中删除的密钥不会在下次调用response.json()
时反映出来
在删除所需键之前,应将返回值response.json()
保存到变量中:
data = response.json()
del data['results'][0]['logs']
print(data)
那不是字典;这是一个包含字典的列表,
del theList[0][“logs”]
可以完成这项工作。我已经尝试过了,错误是“KeyError:0”。您可以使用type(response)
检查您的响应的数据类型并发布结果吗?如果之后再次执行response.json()
操作,您将从响应中重新创建dict/list,所以无论你以前做过什么都不会影响它。您只需要执行一次response.json()
并将其存储在变量中。然后尝试delresponse['results'][0][“logs”]