0

I have tried looping through this list and the dictionary at its index. I intend to get the key-value pairs into a new dictionary.

travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
},
{
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]

new_dict = {}
for key in travel_log[0]:
    new_dict = key
print(new_dict)

The code above just loops into it and adds the last key looped over to the new dictionary, meanwhile, I want all the key values "countries", "visits" and "cities" to be there.

wanicedude
  • 17
  • 1
  • a similar question here: https://stackoverflow.com/questions/73675464/sum-of-only-couple-of-indexes-of-lists-in-a-dictionary/73837559#73837559 – D.L Sep 25 '22 at 12:21
  • Does this answer your question? [Sum of only couple of indexes of lists in a dictionary](https://stackoverflow.com/questions/73675464/sum-of-only-couple-of-indexes-of-lists-in-a-dictionary) – D.L Sep 25 '22 at 12:22

2 Answers2

1

travel_log is a list of dictionaries list(dict()) if want to copy the first element of the travel_log to a new dictionary then do this:

new_dict = travel_log[0]

upd: as Serge Ballesta noticed below, the dictionary is a mutable data type; In oder to create a new object you can use dict()

new_dict = dict(travel_log[0]) 
4snok
  • 62
  • 5
0

Try this

new_dict = {}
for key,value in travel_log[0].items():
    new_dict[key] = value
print(new_dict)

Output

{'country': 'France',
 'visits': 12,
 'cities': ['Paris', 'Lille', 'Dijon']}
codester_09
  • 5,622
  • 2
  • 5
  • 27