python列表中的小写字典项

2024-06-28 11:38:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将字典中列表中的所有键都小写。我实际上有一个代码,它在for循环中打印出我想要的小写输出。我使用的是小写的字典理解,但我不知道如何将更改后的值附加到我的列表中

amdardict = [{'1031': 98, '1032': 1, '33007': 70, 'AIRCRAFT_FLIGHT_NUMBER': 'CNFNXQ', 'DAY': 5, 'HEIGHT_OR_ALTITUDE': 1490.0, 'HOUR': 0, 'LATITUDE': 39.71, 'LONGITUDE': -41.79, 'MINUTE': 0, 'MONTH': 10, 'PHASE_OF_AIRCRAFT_FLIGHT': 5, 'TEMPERATURE_DRY_BULB_TEMPERATURE': 289.0, 'WIND_DIRECTION': 219, 'WIND_SPEED': 3.0, 'YEAR': 2019}
{'12101': 248.75, '4006': 55, '7010': 6135, '8009': 3, 'aircraft_flight_number': '????????', 'aircraft_registration_number_or_other_identification': 'AU0155', 'aircraft_tail_number': '??????', 'day': 5, 'destination_airport': '???', 'hour': 0, 'latitude': -34.3166, 'longitude': 151.9333, 'minute': 8, 'month': 10, 'observation_sequence_number': 64, 'origination_airport': '???', 'wind_direction': 208, 'wind_speed': 23.0, 'year': 2019}
]

for d in amdardict: print(dict((k.lower(), v) for k, v in d.items()))

Tags: 代码innumber列表for字典flightwind
2条回答

为什么要修改原始列表?是否可以创建一个新的空列表,并稍微修改代码以附加到新列表而不是打印:

new_list = []
for d in amdardict: 
    new_list.append(dict((k.lower(), v)     for k, v in d.items()))

要就地更改键,可以使用dict.pop方法

>>> # Copy the list in case we make a mistake
>>> import copy
>>> backup = copy.deepcopy(amdardict)
>>> for d in amdardict:
...     # <ake a list of keys() because we can't loop over keys()
...     # and change keys simultaneously
...     for k in list(d.keys()):
...         if not k.islower():
                # pop removes the key from the dict and returns the value
...             d[k.lower()] = d.pop(k) 
... 
>>> amdardict
[{'aircraft_flight_number': 'CNFNXQ', 'day': 5, 'height_or_altitude': 1490.0, 'temperature_dry_bulb_temperature': 289.0, 'wind_direction': 219, 'wind_speed': 3.0, 'year': 2019, 'hour': 0, 'latitude': 39.71, 'longitude': -41.79, 'minute': 0, 'month': 10, 'phase_of_aircraft_flight': 5, '1031': 98, '1032': 1, '33007': 70}, {'aircraft_flight_number': '????????', 'aircraft_registration_number_or_other_identification': 'AU0155', 'aircraft_tail_number': '??????', 'day': 5, 'destination_airport': '???', 'hour': 0, 'latitude': -34.3166, 'longitude': 151.9333, 'minute': 8, 'month': 10, 'observation_sequence_number': 64, 'origination_airport': '???', 'wind_direction': 208, 'wind_speed': 23.0, 'year': 2019, '12101': 248.75, '4006': 55, '7010': 6135, '8009': 3}]

相关问题 更多 >