Python dictionary operation details and dictionary built in method sharing

  • 2020-06-23 00:55:16
  • OfStack

create

Method 1:


>>> dict1 = {}
>>> dict2 = {'name': 'earth', 'port': 80}
>>> dict1, dict2
({}, {'port': 80, 'name': 'earth'})

Approach 2: Starting with Python 2.2, you can use a factory method, passing in a tuple of a list as a parameter


>>> fdict = dict((['x', 1], ['y', 2]))
>>> fdict
{'y': 2, 'x': 1}

Method 3:

Starting with Python 2.3, a handy built-in method, fromkeys(), can be used to create a "default" dictionary in which elements have the same value (if not given, None by default, which is a bit like my framework's oneObject method):


>>> ddict = {}.fromkeys(('x', 'y'), -1) 
>>> ddict
{'y': -1, 'x': -1}
>>>
>>> edict = {}.fromkeys(('foo', 'bar'))
>>> edict
{'foo': None, 'bar': None}

Access the values in the dictionary

To iterate over a dictionary, you simply loop through its keys like this:


>>> dict2 = {'name': 'earth', 'port': 80}
>>>
>>>> for key in dict2.keys():
... print 'key=%s, value=%s' % (key, dict2[key])
...
key=name, value=earth
key=port, value=80

Starting with Python 2.2, you can traverse the dictionary directly in the for loop.


>>> dict2 = {'name': 'earth', 'port': 80}
>>>
>>>> for key in dict2:
... print 'key=%s, value=%s' % (key, dict2[key])
...
key=name, value=earth
key=port, value=80

To determine whether a key-value pair exists, use the has_key() or in, not in operators


>>> 'server' in dict2 #  or  dict2.has_key('server')
False
>>> 'name' in dict #  or  dict2.has_key('name')
True
>>> dict2['name']
'earth'

1 dictionary example of mixing Numbers and strings:


>>> dict3 = {}
>>> dict3[1] = 'abc'
>>> dict3['1'] = 3.14159
>>> dict3[3.2] = 'xyz'
>>> dict3
{3.2: 'xyz', 1: 'abc', '1': 3.14159}

Update the dictionary

Take coverage update

In the above example dict2 [' name] = 'earth';

Update dict2 [' name] = 'abc';

Delete dictionary elements and dictionaries

del dict2['name'] # delete entries with the key "name"

dict2.clear () # Delete all entries in dict2

del dict2 # delete the entire dict2 dictionary

dict2.pop ('name') # Delete and return the entry with the key 'name'


dict2 = {'name': 'earth', 'port': 80}
>>> dict2.keys()
['port', 'name']
>>>
>>> dict2.values()
[80, 'earth']
>>>
>>> dict2.items()
[('port', 80), ('name', 'earth')]
>>>
>>> for eachKey in dict2.keys():
... print 'dict2 key', eachKey, 'has value', dict2[eachKey]
...
dict2 key port has value 80
dict2 key name has value earth

The update() method can be used to add the contents of one dictionary to another


dict3 = {'server': 'http', 'port': 80, 'host': 'venus'}
>>> dict3.clear()
>>> dict3
{}

Map type-dependent functions


>>> dict(x=1, y=2)
{'y': 2, 'x': 1}
>>> dict8 = dict(x=1, y=2)
>>> dict8
{'y': 2, 'x': 1}
>>> dict9 = dict(**dict8)
>>> dict9
{'y': 2, 'x': 1}
 
dict9 = dict8.copy()

Dictionary built-in method

方法名字 操作
dict.clear() 删除字典中所有元素
dict.copy() 返回字典(浅复制)的1个副本
dict.fromkeysc(seq,val=None) 创建并返回1个新字典,以seq 中的元素做该字典的键,val 做该字典中所有键对应的初始值(如果不提供此值,则默认为None)
dict.get(key,default=None) 对字典dict 中的键key,返回它对应的值value,如果字典中不存在此键,则返回default 的值(注意,参数default 的默认值为None)
dict.has_key(key) 如果键(key)在字典中存在,返回True,否则返回False. 在Python2.2版本引入in 和not in 后,此方法几乎已废弃不用了,但仍提供1个 可工作的接口。
dict.items() 返回1个包含字典中(键, 值)对元组的列表
dict.keys() 返回1个包含字典中键的列表
dict.values() 返回1个包含字典中所有值的列表
dict.iter() 方法iteritems(), iterkeys(), itervalues()与它们对应的非迭代方法1样,不同的是它们返回1个迭代子,而不是1个列表。
dict.pop(key[, default]) 和方法get()相似,如果字典中key 键存在,删除并返回dict[key],如果key 键不存在,且没有给出default 的值,引发KeyError 异常。
dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 键,由dict[key]=default 为它赋值。
dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 键,由dict[key]=default 为它赋值。

conclusion

That's all I have to say about the Python dictionary operation and how to build it. Those who are interested can continue to see this site:

python Basic Exercises of a few simple games

Python Basic exercises user login implementation code sharing

Basic Analysis of Python Object-oriented Programming (1)

If there is any deficiency, please let me know. Thank you for your support!


Related articles: