0

I have a python list that is compromised of multiple dictionaries within a list.

{"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"}

I am trying to add the key minute for all of the dictionaries within the list, and don't care for it's value at the moment, and run into a runtime error, which after reading on the reasoning is expected.

{"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 Answer 1

4

Use the standard dictionary assignment syntax in a loop to add a new key/value pair to each dictionary in your list:

>>> 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'}]

You can read more about dictionaries in the docs here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.