How can I add new keys to a dictionary?

前端 未结 16 2665
梦毁少年i
梦毁少年i 2020-11-22 00:40

Is it possible to add a key to a Python dictionary after it has been created?

It doesn\'t seem to have an .add() method.

相关标签:
16条回答
  • 2020-11-22 01:09

    So many answers and still everybody forgot about the strangely named, oddly behaved, and yet still handy dict.setdefault()

    This

    value = my_dict.setdefault(key, default)
    

    basically just does this:

    try:
        value = my_dict[key]
    except KeyError: # key not found
        value = my_dict[key] = default
    

    e.g.

    >>> mydict = {'a':1, 'b':2, 'c':3}
    >>> mydict.setdefault('d', 4)
    4 # returns new value at mydict['d']
    >>> print(mydict)
    {'a':1, 'b':2, 'c':3, 'd':4} # a new key/value pair was indeed added
    # but see what happens when trying it on an existing key...
    >>> mydict.setdefault('a', 111)
    1 # old value was returned
    >>> print(mydict)
    {'a':1, 'b':2, 'c':3, 'd':4} # existing key was ignored
    
    0 讨论(0)
  • 2020-11-22 01:10

    first to check whether the key already exists

    a={1:2,3:4}
    a.get(1)
    2
    a.get(5)
    None
    

    then you can add the new key and value

    0 讨论(0)
  • 2020-11-22 01:12

    Here's another way that I didn't see here:

    >>> foo = dict(a=1,b=2)
    >>> foo
    {'a': 1, 'b': 2}
    >>> goo = dict(c=3,**foo)
    >>> goo
    {'c': 3, 'a': 1, 'b': 2}
    

    You can use the dictionary constructor and implicit expansion to reconstruct a dictionary. Moreover, interestingly, this method can be used to control the positional order during dictionary construction (post Python 3.6). In fact, insertion order is guaranteed for Python 3.7 and above!

    >>> foo = dict(a=1,b=2,c=3,d=4)
    >>> new_dict = {k: v for k, v in list(foo.items())[:2]}
    >>> new_dict
    {'a': 1, 'b': 2}
    >>> new_dict.update(newvalue=99)
    >>> new_dict
    {'a': 1, 'b': 2, 'newvalue': 99}
    >>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
    >>> new_dict
    {'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
    >>> 
    

    The above is using dictionary comprehension.

    0 讨论(0)
  • 2020-11-22 01:12

    add dictionary key, value class.

    class myDict(dict):
    
        def __init__(self):
            self = dict()
    
        def add(self, key, value):
            #self[key] = value # add new key and value overwriting any exiting same key
            if self.get(key)!=None:
                print('key', key, 'already used') # report if key already used
            self.setdefault(key, value) # if key exit do nothing
    
    
    ## example
    
    myd = myDict()
    name = "fred"
    
    myd.add('apples',6)
    print('\n', myd)
    myd.add('bananas',3)
    print('\n', myd)
    myd.add('jack', 7)
    print('\n', myd)
    myd.add(name, myd)
    print('\n', myd)
    myd.add('apples', 23)
    print('\n', myd)
    myd.add(name, 2)
    print(myd)
    
    0 讨论(0)
  • 2020-11-22 01:13
    d = {'key': 'value'}
    print(d)
    # {'key': 'value'}
    d['mynewkey'] = 'mynewvalue'
    print(d)
    # {'key': 'value', 'mynewkey': 'mynewvalue'}
    

    you create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten. —R. Navega

    0 讨论(0)
  • 2020-11-22 01:13

    You can create one:

    class myDict(dict):
    
        def __init__(self):
            self = dict()
    
        def add(self, key, value):
            self[key] = value
    
    ## example
    
    myd = myDict()
    myd.add('apples',6)
    myd.add('bananas',3)
    print(myd)
    

    Gives:

    >>> 
    {'apples': 6, 'bananas': 3}
    
    0 讨论(0)
提交回复
热议问题