Python dictionaries-How to keep the new value from overwriting the previous value?

前端 未结 4 631
孤独总比滥情好
孤独总比滥情好 2020-12-21 10:02

I want to create a Dictionary called \"First\" (as in First Name) that will store numerous first names which are all stored in the dictionary via a function. The idea is th

4条回答
  •  悲哀的现实
    2020-12-21 10:27

    You should probably be storing the list of names as a list, rather than a dictionary. So you would have:

    data['Names'] = {}
    data['Names']['first'] = [] #note the brackets here instead of curlies
    data['Names']['first'] = [value1, value2]
    

    To add one after instantiation, you can do:

    data['Names']['first'].append(another_first_name)
    

    Lists are zero-indexed, so to get the 1st first name, you can say:

    data['Names']['first'][0]
    

提交回复
热议问题