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

前端 未结 4 604
孤独总比滥情好
孤独总比滥情好 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:07

    Turn data['Names']['first'] in a list and append to it:

    data['Names'] = {}
    data['Names']['first'] = []
    
    def store(data, value):
        data['Names']['first'].append(value)
    
    0 讨论(0)
  • 2020-12-21 10:25

    Python < 2.5 doesn't have defaultdict, however you can achieve the same thing in with ordinary dict too.

    >>> names = {}
    >>> name_list = [('Jon', 'Skeet'), ('Jeff', 'Atwood'), ('Joel', 'Spolsky')]
    >>> for first, last in name_list:
            names.setdefault('first', []).append(first)
            names.setdefault('last', []).append(last)
    >>> print names
    {'first': ['Jon', 'Jeff', 'Joel'], 'last': ['Skeet', 'Atwood', 'Spolsky']}
    

    setdefault returns the existing value if the key already exists in dict, or sets the new value and returns the newly set value if the key doesn't exist.

    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-12-21 10:29

    Have a look at collections.defaultdict. Then you can do things like:

    from collections import defaultdict
    
    data['Names'] = defaultdict(list) # Or pass set instead of list.
    data['Names']['first'].append("Bob")
    data['Names']['first'].append("Jane")
    data['Names']['last'].extend("T", "Mart")
    
    0 讨论(0)
提交回复
热议问题