向字典中添加新键?

时间:2023-02-01 11:21:45

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.

在Python字典被创建之后,是否可能向它添加一个键?它似乎没有.add()方法。

19 个解决方案

#1


2424  

>>> d = {'key':'value'}
>>> print(d)
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print(d)
{'mynewkey': 'mynewvalue', 'key': 'value'}

#2


840  

>>> x = {1:2}
>>> print x
{1: 2}

>>> x.update({3:4})
>>> print x
{1: 2, 3: 4}

#3


541  

I feel like consolidating info about Python dictionaries:

我想整合Python字典的信息:

Creating an empty dictionary

data = {}
# OR
data = dict()

Creating a dictionary with initial values

data = {'a':1,'b':2,'c':3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1),('b',2),('c',3))}

Inserting/Updating a single value

data['a']=1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a':1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)

Inserting/Updating multiple values

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Creating a merged dictionary without modifying originals

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

Deleting items in dictionary

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

Check if a key is already in dictionary

key in data

Iterate through pairs in a dictionary

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

Create a dictionary from 2 lists

data = dict(zip(list_with_keys, list_with_values))

Feel free to add more!

请随意添加更多内容!

#4


130  

Yeah, it's pretty easy. Just do the following:

是的,它很简单。执行以下操作:

dict["key"] = "value"

#5


105  

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

Yes it is possible, and it does have a method that implements this, but you don't want to use it directly.

是的,这是可能的,而且它确实有一个实现这个的方法,但是您不希望直接使用它。

To demonstrate how and how not to use it, let's create an empty dict with the dict literal, {}:

为了演示如何使用它,以及如何不使用它,让我们创建一个空的具有dict类型({}:

my_dict = {}

Best Practice 1: Subscript notation

To update this dict with a single new key and value, you can use the subscript notation (see Mappings here) that provides for item assignment:

要用一个新的键和值更新这个命令,您可以使用下标表示法(见这里的映射)来提供项分配:

my_dict['new key'] = 'new value'

my_dict is now:

my_dict现在:

{'new key': 'new value'}

Best Practice 2: The update method - 2 ways

We can also update the dict with multiple values efficiently as well using the update method. We may be unnecessarily creating an extra dict here, so we hope our dict has already been created and came from or was used for another purpose:

我们还可以使用update方法有效地用多个值更新敕令。我们可能在这里不必要地创造了一个额外的法令,所以我们希望我们的法令已经被创造并且来自或者被用于其他目的:

my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})

my_dict is now:

my_dict现在:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}

Another efficient way of doing this with the update method is with keyword arguments, but since they have to be legitimate python words, you can't have spaces or special symbols or start the name with a number, but many consider this a more readable way to create keys for a dict, and here we certainly avoid creating an extra unnecessary dict:

这样做的另一个有效的方式与关键字参数与更新方法,但由于它们必须是合法的python语言,你不能有空格或特殊符号或启动的名字与号码,但许多人认为这更可读的方式来创建密钥dict,这里我们当然避免创建一个额外的不必要的dict类型:

my_dict.update(foo='bar', foo2='baz')

and my_dict is now:

和my_dict现在:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 
 'foo': 'bar', 'foo2': 'baz'}

So now we have covered three Pythonic ways of updating a dict.

现在我们已经介绍了三种毕达哥拉斯式的更新命令的方法。


Magic method, __setitem__, and why it should be avoided

There's another way of updating a dict that you shouldn't use, which uses the __setitem__ method. Here's an example of how one might use the __setitem__ method to add a key-value pair to a dict, and a demonstration of the poor performance of using it:

还有一种方法可以更新不应该使用的命令,它使用__setitem__方法。下面是一个使用__setitem__方法将键-值对添加到dict类型的示例,并演示使用它的糟糕性能:

>>> d = {}
>>> d.__setitem__('foo', 'bar')
>>> d
{'foo': 'bar'}


>>> def f():
...     d = {}
...     for i in xrange(100):
...         d['foo'] = i
... 
>>> def g():
...     d = {}
...     for i in xrange(100):
...         d.__setitem__('foo', i)
... 
>>> import timeit
>>> number = 100
>>> min(timeit.repeat(f, number=number))
0.0020880699157714844
>>> min(timeit.repeat(g, number=number))
0.005071878433227539

So we see that using the subscript notation is actually much faster than using __setitem__. Doing the Pythonic thing, that is, using the language in the way it was intended to be used, usually is both more readable and computationally efficient.

所以我们看到使用下标符号实际上比使用__setitem__要快得多。做勾股定理的事情,也就是说,以预期的方式使用这种语言,通常都更容易读懂,计算效率也更高。

#6


72  

dictionary[key] = value

#7


44  

If you want to add a dictionary within a dictionary you can do it this way.

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

Example: Add a new entry to your dictionary & sub dictionary

示例:在字典和子字典中添加一个新条目

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)

Output:

输出:

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

NOTE: Python requires that you first add a sub

注意:Python要求您首先添加一个sub

dictionary["dictionary_within_a_dictionary"] = {}

before adding entries.

之前添加条目。

#8


31  

The orthodox syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could do:

正统的语法是d[key] = value,但是如果你的键盘缺少方括号键,你可以这样做:

d.__setitem__(key, value)

In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax. See http://www.diveintopython.net/object_oriented_framework/special_class_methods.html

实际上,定义__getitem__和__setitem__方法可以使您自己的类支持方括号语法。参见http://www.diveintopython.net/object_oriented_framework/special_class_methods.html

#9


24  

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}

#10


23  

This popular question addresses functional methods of merging dictionaries a and b.

这个常见的问题涉及合并字典a和字典b的功能方法。

Here are some of the more straightforward methods (tested in Python 3)...

下面是一些更简单的方法(在Python 3中测试)……

c = dict( a, **b ) ## see also https://*.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )

Note: The first method above only works if the keys in b are strings.

注意:上面的第一个方法只在b中的键是字符串时有效。

To add or modify a single element, the b dictionary would contain only that one element...

要添加或修改单个元素,b字典将只包含该元素…

c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'

This is equivalent to...

这相当于……

def functional_dict_add( dictionary, key, value ):
   temp = dictionary.copy()
   temp[key] = value
   return temp

c = functional_dict_add( a, 'd', 'dog' )

#11


15  

data = {}
data['a'] = 'A'
data['b'] = 'B'

for key, value in data.iteritems():
    print "%s-%s" % (key, value)

results in

结果

a-A
b-B

#12


9  

This is exactly how I would do it: # fixed data with sapce

这正是我要做的:使用sapce的#固定数据

data = {}
data['f'] = 'F'
data['c'] = 'C'

for key, value in data.iteritems():
    print "%s-%s" % (key, value)

This works for me. Enjoy!

这适合我。享受吧!

#13


8  

we can add new keys to dictionary by this way:

我们可以这样给字典添加新键:

Dictionary_Name[New_Key_Name] = New_Key_Value

Dictionary_Name[New_Key_Name]= New_Key_Value

Here is the Example:

下面是例子:

# This is my dictionary
my_dict = {'Key1': 'Value1', 'Key2': 'Value2'}
# Now add new key in my dictionary
my_dict['key3'] = 'Value3'
# Print updated dictionary
print my_dict

Output:

输出:

{'key3': 'Value3', 'Key2': 'Value2', 'Key1': 'Value1'}

#14


6  

It has a update method which you can use like this:

它有一个更新方法,你可以这样使用:

dict.update({"key" : "value"})

dict.update({“关键”:“价值”})

#15


6  

Let's pretend you want to live in the immutable world and do NOT want to modify the original but want to create a new dict that is the result of adding a new key to the original.

让我们假设您希望生活在一个不变的世界中,并且不希望修改原始版本,而是希望创建一个新命令,这是向原始版本添加新键的结果。

In Python 3.5+ you can do:

在Python 3.5+中,您可以:

params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}

The Python 2 equivalent is:

等效的Python 2是:

params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})

After either of these:

在这两种:

params is still equal to {'a': 1, 'b': 2}

params仍然等于{'a': 1, 'b': 2}

and

new_params is equal to {'a': 1, 'b': 2, 'c': 3}

new_params等于{'a': 1, 'b': 2, 'c': 3}

There will be times when you don't want to modify the original (you only want the result of adding to the original). I find this a refreshing alternative to the following:

有时候,您不想修改原来的(您只需要添加到原始的结果)。我发现这是一个令人耳目一新的替代方案:

params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3

or

params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params.update({'c': 3})

Reference: https://*.com/a/2255892/514866

参考:https://*.com/a/2255892/514866

#16


3  

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

有这么多的答案,但每个人都忘记了奇怪的名字,奇怪的行为,但仍然方便的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

#17


3  

Basically two simple ways with which you can add new key in the dict

基本上有两种简单的方法可以在命令中添加新键。

dict_input = {'one': 1, 'two': 2, 'three': 3}

#1. Set a new value
dict_input['four'] = 4

#2. or use the update() function
dict_input.update({'five': 5})

#18


1  

Use the subscript assignment operator:

使用下标赋值操作符:

d['x'] = "value"

Don't forget that Python's key can by anything hashable which means bool, int, string even a tuple or any objects hashable.

不要忘记Python的键可以通过任何可清洗的方式进行,这意味着bool、int、string甚至tuple或任何对象都可以清洗。

#19


0  

I would do it like this. Watch out for the directory[name]=number part.

我应该这样做。注意目录[name]=数字部分。

n = int(raw_input())
directory={}
entry={}
# store the values as if they appear in the stdin
for i in xrange(n):
    name, number = raw_input().split()
    directory[name]=number

#  query the values    
while (True):
    queryname = (str) (raw_input())
    try:
        strdisp = queryname + "=" + directory[queryname]
        print strdisp
    except:
      print 'Not found'

#1


2424  

>>> d = {'key':'value'}
>>> print(d)
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print(d)
{'mynewkey': 'mynewvalue', 'key': 'value'}

#2


840  

>>> x = {1:2}
>>> print x
{1: 2}

>>> x.update({3:4})
>>> print x
{1: 2, 3: 4}

#3


541  

I feel like consolidating info about Python dictionaries:

我想整合Python字典的信息:

Creating an empty dictionary

data = {}
# OR
data = dict()

Creating a dictionary with initial values

data = {'a':1,'b':2,'c':3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1),('b',2),('c',3))}

Inserting/Updating a single value

data['a']=1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a':1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)

Inserting/Updating multiple values

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Creating a merged dictionary without modifying originals

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

Deleting items in dictionary

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

Check if a key is already in dictionary

key in data

Iterate through pairs in a dictionary

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

Create a dictionary from 2 lists

data = dict(zip(list_with_keys, list_with_values))

Feel free to add more!

请随意添加更多内容!

#4


130  

Yeah, it's pretty easy. Just do the following:

是的,它很简单。执行以下操作:

dict["key"] = "value"

#5


105  

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

Yes it is possible, and it does have a method that implements this, but you don't want to use it directly.

是的,这是可能的,而且它确实有一个实现这个的方法,但是您不希望直接使用它。

To demonstrate how and how not to use it, let's create an empty dict with the dict literal, {}:

为了演示如何使用它,以及如何不使用它,让我们创建一个空的具有dict类型({}:

my_dict = {}

Best Practice 1: Subscript notation

To update this dict with a single new key and value, you can use the subscript notation (see Mappings here) that provides for item assignment:

要用一个新的键和值更新这个命令,您可以使用下标表示法(见这里的映射)来提供项分配:

my_dict['new key'] = 'new value'

my_dict is now:

my_dict现在:

{'new key': 'new value'}

Best Practice 2: The update method - 2 ways

We can also update the dict with multiple values efficiently as well using the update method. We may be unnecessarily creating an extra dict here, so we hope our dict has already been created and came from or was used for another purpose:

我们还可以使用update方法有效地用多个值更新敕令。我们可能在这里不必要地创造了一个额外的法令,所以我们希望我们的法令已经被创造并且来自或者被用于其他目的:

my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})

my_dict is now:

my_dict现在:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}

Another efficient way of doing this with the update method is with keyword arguments, but since they have to be legitimate python words, you can't have spaces or special symbols or start the name with a number, but many consider this a more readable way to create keys for a dict, and here we certainly avoid creating an extra unnecessary dict:

这样做的另一个有效的方式与关键字参数与更新方法,但由于它们必须是合法的python语言,你不能有空格或特殊符号或启动的名字与号码,但许多人认为这更可读的方式来创建密钥dict,这里我们当然避免创建一个额外的不必要的dict类型:

my_dict.update(foo='bar', foo2='baz')

and my_dict is now:

和my_dict现在:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 
 'foo': 'bar', 'foo2': 'baz'}

So now we have covered three Pythonic ways of updating a dict.

现在我们已经介绍了三种毕达哥拉斯式的更新命令的方法。


Magic method, __setitem__, and why it should be avoided

There's another way of updating a dict that you shouldn't use, which uses the __setitem__ method. Here's an example of how one might use the __setitem__ method to add a key-value pair to a dict, and a demonstration of the poor performance of using it:

还有一种方法可以更新不应该使用的命令,它使用__setitem__方法。下面是一个使用__setitem__方法将键-值对添加到dict类型的示例,并演示使用它的糟糕性能:

>>> d = {}
>>> d.__setitem__('foo', 'bar')
>>> d
{'foo': 'bar'}


>>> def f():
...     d = {}
...     for i in xrange(100):
...         d['foo'] = i
... 
>>> def g():
...     d = {}
...     for i in xrange(100):
...         d.__setitem__('foo', i)
... 
>>> import timeit
>>> number = 100
>>> min(timeit.repeat(f, number=number))
0.0020880699157714844
>>> min(timeit.repeat(g, number=number))
0.005071878433227539

So we see that using the subscript notation is actually much faster than using __setitem__. Doing the Pythonic thing, that is, using the language in the way it was intended to be used, usually is both more readable and computationally efficient.

所以我们看到使用下标符号实际上比使用__setitem__要快得多。做勾股定理的事情,也就是说,以预期的方式使用这种语言,通常都更容易读懂,计算效率也更高。

#6


72  

dictionary[key] = value

#7


44  

If you want to add a dictionary within a dictionary you can do it this way.

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

Example: Add a new entry to your dictionary & sub dictionary

示例:在字典和子字典中添加一个新条目

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)

Output:

输出:

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

NOTE: Python requires that you first add a sub

注意:Python要求您首先添加一个sub

dictionary["dictionary_within_a_dictionary"] = {}

before adding entries.

之前添加条目。

#8


31  

The orthodox syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could do:

正统的语法是d[key] = value,但是如果你的键盘缺少方括号键,你可以这样做:

d.__setitem__(key, value)

In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax. See http://www.diveintopython.net/object_oriented_framework/special_class_methods.html

实际上,定义__getitem__和__setitem__方法可以使您自己的类支持方括号语法。参见http://www.diveintopython.net/object_oriented_framework/special_class_methods.html

#9


24  

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}

#10


23  

This popular question addresses functional methods of merging dictionaries a and b.

这个常见的问题涉及合并字典a和字典b的功能方法。

Here are some of the more straightforward methods (tested in Python 3)...

下面是一些更简单的方法(在Python 3中测试)……

c = dict( a, **b ) ## see also https://*.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )

Note: The first method above only works if the keys in b are strings.

注意:上面的第一个方法只在b中的键是字符串时有效。

To add or modify a single element, the b dictionary would contain only that one element...

要添加或修改单个元素,b字典将只包含该元素…

c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'

This is equivalent to...

这相当于……

def functional_dict_add( dictionary, key, value ):
   temp = dictionary.copy()
   temp[key] = value
   return temp

c = functional_dict_add( a, 'd', 'dog' )

#11


15  

data = {}
data['a'] = 'A'
data['b'] = 'B'

for key, value in data.iteritems():
    print "%s-%s" % (key, value)

results in

结果

a-A
b-B

#12


9  

This is exactly how I would do it: # fixed data with sapce

这正是我要做的:使用sapce的#固定数据

data = {}
data['f'] = 'F'
data['c'] = 'C'

for key, value in data.iteritems():
    print "%s-%s" % (key, value)

This works for me. Enjoy!

这适合我。享受吧!

#13


8  

we can add new keys to dictionary by this way:

我们可以这样给字典添加新键:

Dictionary_Name[New_Key_Name] = New_Key_Value

Dictionary_Name[New_Key_Name]= New_Key_Value

Here is the Example:

下面是例子:

# This is my dictionary
my_dict = {'Key1': 'Value1', 'Key2': 'Value2'}
# Now add new key in my dictionary
my_dict['key3'] = 'Value3'
# Print updated dictionary
print my_dict

Output:

输出:

{'key3': 'Value3', 'Key2': 'Value2', 'Key1': 'Value1'}

#14


6  

It has a update method which you can use like this:

它有一个更新方法,你可以这样使用:

dict.update({"key" : "value"})

dict.update({“关键”:“价值”})

#15


6  

Let's pretend you want to live in the immutable world and do NOT want to modify the original but want to create a new dict that is the result of adding a new key to the original.

让我们假设您希望生活在一个不变的世界中,并且不希望修改原始版本,而是希望创建一个新命令,这是向原始版本添加新键的结果。

In Python 3.5+ you can do:

在Python 3.5+中,您可以:

params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}

The Python 2 equivalent is:

等效的Python 2是:

params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})

After either of these:

在这两种:

params is still equal to {'a': 1, 'b': 2}

params仍然等于{'a': 1, 'b': 2}

and

new_params is equal to {'a': 1, 'b': 2, 'c': 3}

new_params等于{'a': 1, 'b': 2, 'c': 3}

There will be times when you don't want to modify the original (you only want the result of adding to the original). I find this a refreshing alternative to the following:

有时候,您不想修改原来的(您只需要添加到原始的结果)。我发现这是一个令人耳目一新的替代方案:

params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3

or

params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params.update({'c': 3})

Reference: https://*.com/a/2255892/514866

参考:https://*.com/a/2255892/514866

#16


3  

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

有这么多的答案,但每个人都忘记了奇怪的名字,奇怪的行为,但仍然方便的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

#17


3  

Basically two simple ways with which you can add new key in the dict

基本上有两种简单的方法可以在命令中添加新键。

dict_input = {'one': 1, 'two': 2, 'three': 3}

#1. Set a new value
dict_input['four'] = 4

#2. or use the update() function
dict_input.update({'five': 5})

#18


1  

Use the subscript assignment operator:

使用下标赋值操作符:

d['x'] = "value"

Don't forget that Python's key can by anything hashable which means bool, int, string even a tuple or any objects hashable.

不要忘记Python的键可以通过任何可清洗的方式进行,这意味着bool、int、string甚至tuple或任何对象都可以清洗。

#19


0  

I would do it like this. Watch out for the directory[name]=number part.

我应该这样做。注意目录[name]=数字部分。

n = int(raw_input())
directory={}
entry={}
# store the values as if they appear in the stdin
for i in xrange(n):
    name, number = raw_input().split()
    directory[name]=number

#  query the values    
while (True):
    queryname = (str) (raw_input())
    try:
        strdisp = queryname + "=" + directory[queryname]
        print strdisp
    except:
      print 'Not found'