首页 > 解决方案 > 如何从 python 中的输出字典中删除项目?

问题描述

我需要在最终输出中创建一个函数:

[{'open': [{'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 0}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 1}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 2}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 3}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 4}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 5}, {'is_overnight': False, 'start': '1100', 'end': '2100', 'day': 6}], 'hours_type': 'REGULAR', 'is_open_now': False}]

我不想要'is_overnight' 和钥匙。我该怎么做?

试过这个:

def is_clocked(business_id):
    #import pdb; pdb.set_trace()
    try:
        clocked_ind = get_business(API_KEY, business_id)
        clocked_ind1 = clocked_ind['hours']
    except:
        clocked_ind1 = 'None'
    return clocked_ind1
clocked_ind = is_clocked(b_id)
print(clocked_ind)
#testing
hours = clocked_ind #.pop("is_overnight")
hours.pop('is_overnight')
print(hours)

不工作!

标签: pythonspyder

解决方案


遍历 each 的listand deleteis_overnight键及其值dict。喜欢:

my_list = [{'open': [{'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 0},
           {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 1},
           {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 2},
           {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 3},
           {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 4},
           {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 5},
           {'is_overnight': False, 'start': '1100', 'end': '2100', 'day': 6}], 'hours_type': 'REGULAR',
  'is_open_now': False}]

for i in my_list[0]["open"]:
    del i["is_overnight"]

print(my_list)

输出:

[{'open': [{'start': '1100', 'end': '2200', 'day': 0}, {'start': '1100', 'end': '2200', 'day': 1}, {'start': '1100', 'end': '2200', 'day': 2}, {'start': '1100', 'end': '2200', 'day': 3}, {'start': '1100', 'end': '2200', 'day': 4}, {'start': '1100', 'end': '2200', 'day': 5}, {'start': '1100', 'end': '2100', 'day': 6}], 'hours_type': 'REGULAR', 'is_open_now': False}]

推荐阅读