【问题标题】:Lowercase dictionary items within a list python列表python中的小写字典项
【发布时间】:2019-11-01 03:33:52
【问题描述】:

我正在尝试将列表中字典中的所有键都小写。我实际上有一个代码可以在 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()))

【问题讨论】:

    标签: python dictionary lowercase


    【解决方案1】:

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

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

    【讨论】:

    • 感谢 J.Behnken,不知道为什么我没有想到这一点。感谢您的正确答案,一旦我有 15 个代表点,我会投票!
    【解决方案2】:

    要就地更改密钥,您可以使用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}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-20
      • 2021-07-11
      • 2012-07-28
      • 2014-10-15
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      相关资源
      最近更新 更多