-3

I have made a simple code of having a dictionary inside a list, how do you add an another element to them? The code is as follow:

Cars = []
Cars.append({"make": "Tesla", "colour": "red"})
print(Cars)
Cars.append({"make": "Toyota", "colour": "green"})
Cars.append({"make": "Ford", "colour": "white"})
print(Cars)

I want it to add a new dictionary element to the list showing year of manufacture so that when I print it shows this

[{'make': Tesla, 'colour': 'red',’year’:2020}
,{"make": "Toyota", "colour": "green",’year’:2020}
,{"make": "Ford", "colour": "white",’year’:2020}
]
  • You have to do this using the list index, like: `Cars[0]['year'] = 2020` – GAEfan Aug 16 '20 at 18:41
  • @GAEfan And how do you know which index? – superb rain Aug 16 '20 at 18:43
  • You don't. You'd have to write a script to test and find the car you want. unless you want to add the same value to all, then just use a loop. – GAEfan Aug 16 '20 at 18:44
  • @GAEfan Why would you do either of those with an index? – superb rain Aug 16 '20 at 18:45
  • @GAEfan thx very much, but do you know why I got marked down, Im kind new to Stackoverflow? – Vibertex Khan Aug 16 '20 at 18:46
  • Does this answer your question? [How can I add new keys to a dictionary?](https://stackoverflow.com/questions/1024847/how-can-i-add-new-keys-to-a-dictionary) – aryanveer Aug 16 '20 at 18:49
  • 1
    Your question is getting voted down because this is a basic question, and you need to do some research first before asking a question on stackoverflow. This is a duplicate question. – aryanveer Aug 16 '20 at 18:50
  • I guess they figure this is a basic python question, and you could have easily Googled it or found similar questions here. This is rather basic list & dictionary ops. – GAEfan Aug 16 '20 at 18:51
  • Thx this really helped. But what will happen if my reputation falls below 0? – Vibertex Khan Aug 16 '20 at 19:00
  • @VibertexKhan If your reputation falls below 0, you'll have to pay a fine. See [here](https://meta.stackexchange.com/q/48037/824076). – superb rain Aug 16 '20 at 19:13

5 Answers5

2
for car in Cars:
    car["year"] = 2020
jreiss1923
  • 464
  • 3
  • 11
1

You need to iterate over the list Cars, and for every element add a new key-value in the dictionary

for car in Cars:
    car['year'] = 2020
aryanveer
  • 628
  • 1
  • 6
  • 17
-1

You could use a for loop to add to each dict in the list like so.

for itm in Cars:
    itm["year"] = 2020
Lewis Morris
  • 1,916
  • 2
  • 28
  • 39
-1
#step 1- loop through the list

for car in Cars:
    #Step 2 - append the dictionary with key as year and value as 2020
    car["year"] = 2020

Hope this help Happy coding

Dev Jalla
  • 1,910
  • 2
  • 13
  • 21
-1

You can simply loop through all element of the list and add, below code will update the Cars list elements

[car.update({'year':2020}) for car in Cars]
Pranjal Gharat
  • 127
  • 1
  • 4