在for循环期间将键添加到列表中的多个Python词典

时间:2019-12-10 01:32:35

标签: python loops dictionary key

我有一个Python列表,其中包含列表中的多个字典。

{"timestamp":"2019-10-05T00:07:50Z","icao_address":"AACAA5","latitude":39.71273649,"longitude":-41.79022217,"altitude_baro":"37000","speed":567,"heading":77,"source":"FM89","collection_type":"satellite","vertical_rate":"0","ingestion_time":"2019-10-05T02:49:47Z"}
{"timestamp":"2019-10-05T00:11:00Z","icao_address":"C03CF1","latitude":48.12194824,"longitude":-44.94451904,"altitude_baro":"36000","speed":565,"heading":73,"source":"FM89","collection_type":"satellite","vertical_rate":"0","ingestion_time":"2019-10-05T02:49:47Z"}
{"timestamp":"2019-10-05T00:11:15Z","icao_address":"A0F4F6","latitude":48.82104492,"longitude":-34.43157489,"altitude_baro":"35000","source":"FM89","collection_type":"satellite","ingestion_time":"2019-10-05T02:49:47Z"}

我正在尝试为列表中的所有字典添加键分钟,并且现在不关心它的值,并遇到运行时错误,在继续阅读后推理是可以预期的。

{"timestamp":"2019-10-05T00:11:15Z","icao_address":"A0F4F6","latitude":48.82104492,"longitude":-34.43157489,"altitude_baro":"35000","source":"FM89","collection_type":"satellite","ingestion_time":"2019-10-05T02:49:47Z", **"minute": "test"**}
{"timestamp":"2019-10-05T00:11:15Z","icao_address":"A0F4F5","latitude":48.82104492,"longitude":-34.43157489,"altitude_baro":"35000","source":"FM89","collection_type":"land","ingestion_time":"2019-10-05T02:49:47Z", **"minute": "test"**}
for data in list:
     for value in data:
         if value == 'latitude' or value == 'longitude':
             data[value] = float('%.2f'%(data[value]))

what are possible ways to add keys to a dictionary while on a loop. 

1 个答案:

答案 0 :(得分:4)

在循环中使用标准字典分配语法,将新的键/值对添加到列表中的每个字典:

>>> x = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]
>>> for data in x:
...     data['minute'] = 'test'
...
>>> x
[{'a': 1, 'b': 2, 'minute': 'test'}, {'a': 3, 'b': 4, 'minute': 'test'}]

您可以在文档here中阅读有关字典的更多信息。