如何向现有词典中添加关键字?它没有.add()方法。


当前回答

这个问题已经得到了令人恶心的回答,但自从我议论获得了很大的牵引力,以下是答案:

添加新密钥而不更新现有字典

如果您在这里试图找出如何添加键并返回新字典(而不修改现有字典),可以使用以下技术来完成

Python>=3.5

new_dict = {**mydict, 'new_key': new_val}

Python<3.5

new_dict = dict(mydict, new_key=new_val)

注意,使用这种方法,您的密钥需要遵循Python中有效标识符名称的规则。

其他回答

在不使用add的情况下向字典中添加关键字

        # Inserting/Updating single value
        # subscript notation method
        d['mynewkey'] = 'mynewvalue' # Updates if 'a' exists, else adds 'a'
        # OR
        d.update({'mynewkey': 'mynewvalue'})
        # OR
        d.update(dict('mynewkey'='mynewvalue'))
        # OR
        d.update('mynewkey'='mynewvalue')
        print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}
        # To add/update multiple keys simultaneously, use d.update():
        x = {3:4, 5:6, 7:8}
        d.update(x)
        print(d) # {'key': 'value', 'mynewkey': 'mynewvalue', 3: 4, 5: 6, 7: 8}
        # update operator |= now works for dictionaries:
        d |= {'c':3,'d':4}
        # Assigning new key value pair using dictionary unpacking.
        data1 = {4:6, 9:10, 17:20}
        data2 = {20:30, 32:48, 90:100}
        data3 = { 38:"value", 99:"notvalid"}
        d = {**data1, **data2, **data3}
        # The merge operator | now works for dictionaries:
        data = data1 | {'c':3,'d':4}
        # Create a dictionary from two lists
        data = dict(zip(list_with_keys, list_with_values))

如果您想在字典中添加字典,可以这样做。

示例:向字典和子字典添加新条目

dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)

输出:

{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}

注意:Python要求您首先添加子

dictionary["dictionary_within_a_dictionary"] = {}

在添加条目之前。

dictionary[key] = value

还有一个名字奇怪,行为怪异,但仍然很方便的dict.setdefault()。

This

value = my_dict.setdefault(key, default)

基本上就是这样:

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

例如。,

>>> 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

添加字典(键、值)类。

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)