This is the second day of my participation in the August Text Challenge.More challenges in August
Dictionary definition
dict
(Dictionary) yesApart from the listPython
Among theThe most flexibleData type of- Dictionaries can also be usedStoring multiple data
- Usually used to store relevant information describing an object
- And a list
- A list is an ordered collection of objects
- A dictionary is an unordered collection of objects
- Dictionary use
{}
Define ordict()
- Dictionary useKey/value pairStore data, used between key-value pairs
.
separated- key
key
Is the index - value
value
Is the data - key 和 valueUsed between
:
separated - The key has to be unique
- Values can take any data type, but keys can only be strings, numbers, or tuples
- key
xiaoming = {
"name": "Xiao Ming"."age": 18."gender": True."height": 1.75
}
Copy the code
Common dictionary operations
- in
IPython
To define aThe dictionary, such as:goods_dict= {}
- The input
goods_dict.
Press theTAB
The key,IPython
You will be promptedThe dictionaryThe following methods can be used:
The usefulness of each method is illustrated in the figure above, so here are a few common methods/operations to test.
A dictionary definition
In [81] :Empty dictionary definition
In [82]: goods_dict = {}
In [83]: goods_dict2 = dict()
In [84] :type(goods_dict)
Out[84] :dict
In [85] :type(goods_dict2)
Out[85] :dict
Copy the code
In [86] :# dictionary definitions with data
^
In [88]: goods_dict ={'name': 'Nuggets T-shirt'.'price': 59}
In [89]: goods_dict2 = dict(name='Nuggets T-shirt', price=59)
In [90] :type(goods_dict), type(goods_dict2)
Out[90] : (dict.dict)
In [91]: goods_dict
Out[91] : {'name': 'Nuggets T-shirt'.'price': 59}
In [92]: goods_dict2
Out[92] : {'name': 'Nuggets T-shirt'.'price': 59}
Copy the code
Dictionary add data
In [94]: goods_dict
Out[94] : {'name': 'Nuggets T-shirt'.'price': 59}
In [95] :# add data
In [96]: goods_dict['size'] = 'L'
In [97]: goods_dict
Out[97] : {'name': 'Nuggets T-shirt'.'price': 59.'size': 'L'}
Copy the code
Dictionary delete data
In [102]: goods_dict
Out[102] : {'name': 'Nuggets T-shirt'.'price': 59.'size': 'L'}
In [103] :Delete key data
In [104] :del goods_dict['size']
In [105]: goods_dict
Out[105] : {'name': 'Nuggets T-shirt'.'price': 59}
In [106]: goods_dict.pop('price')
Out[106] :59
In [107]: goods_dict
Out[107] : {'name': 'Nuggets T-shirt'}
In [108]: goods_dict.popitem()
Out[108] : ('name'.'Nuggets T-shirt')
In [109]: goods_dict
Out[109] : {}Copy the code
Del goods_dict[key] and goods_dict.pop(key) are both specified keys. Delete key-value pairs in the dictionary.
del
There is no return value,pop()
Returns the value of the current delete keyvalue
Goods_dict.popitem () randomly deletes a dictionary key-value pair and returns the deleted key-value pair.
In [111]: goods_dict
Out[111] : {'name': 'Nuggets T-shirt'.'price': 59}
In [112] :Empty the dictionary data
In [113]: goods_dict.clear()
In [114]: goods_dict
Out[114] : {}Copy the code
Dictionary update data
In [116]: goods_dict
Out[116] : {'name': 'Nuggets T-shirt'.'price': 59}
In [117] :Update dictionary data
In [118]: goods_dict['name'] = 'Gold Digger badge'
In [121]: goods_dict
Out[121] : {'name': 'Gold Digger badge'.'price': 59}
In [122]: goods_dict.setdefault('price'.18)
Out[122] :59
In [123]: goods_dict
Out[123] : {'name': 'Gold Digger badge'.'price': 59}
In [124]: goods_dict.setdefault('size'.'M')
Out[124] :'M'
In [125]: goods_dict
Out[125] : {'name': 'Gold Digger badge'.'price': 59.'size': 'M'}
Copy the code
The setdefault() method in the dictionary does not update the key value when the corresponding key already exists in the dictionary, but can only be used to increase the key-value pair. The dictionary [key] is updated if the key exists, and added if it does not exist.
In [127]: goods_dict
Out[127] : {'name': 'Gold Digger badge'.'price': 59.'size': 'M'}
In [128] :# Overall update
In [130]: new_info = {'price': 18.'size': '5cm'}
In [131]: goods_dict.update(new_info)
In [132]: goods_dict
Out[132] : {'name': 'Gold Digger badge'.'price': 18.'size': '5cm'}
In [133]: new_info = {'name': 'Gold Digger Booklet XX'.'author': 'hui'.'price': 19.9}
In [134]: goods_dict.update(new_info)
In [135]: goods_dict
Out[135] : {'name': 'Gold Digger Booklet XX'.'price': 19.9.'size': '5cm'.'author': 'hui'}
Copy the code
The update(new dictionary) method in a dictionary merges the new dictionary into the original dictionary. If the key is the same, it will be updated. If the key is not, it will be added.
The dictionary gets the value of the specified key
In [137]: goods_dict
Out[137] : {'name': 'Gold Digger Booklet XX'.'price': 19.9.'size': '5cm'.'author': 'hui'}
In [138] :Get the value of the specified key
In [139]: goods_dict['name']
Out[139] :'Gold Digger Booklet XX'
In [140]: goods_dict['author']
Out[140] :'hui'
In [141]: goods_dict.get('price')
Out[141] :19.9
In [142]: goods_dict['id'] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-142-b8a93fe9ad6b> in <module>
----> 1 goods_dict['id']
KeyError: 'id'
In [145]: ret = goods_dict.get('id')
In [147] :print(ret)
None
In [148]: count = goods_dict.get('count'.0)
In [149]: count
Out[149] :0
Copy the code
Get (key), which defaults to None if the key does not exist. You can change the default return value, such as goods_dict.get(‘count’, 0), which defaults to 0 if the key does not exist.
other
In [154]: goods_dict
Out[154] : {'name': 'Gold Digger Booklet XX'.'price': 19.9.'author': 'hui'}
In [155] :# The number of key-value pairs in the dictionary
In [156] :len(goods_dict)
Out[156] :3
In [157] :Get all keys in the dictionary
In [158]: goods_dict.keys()
Out[158]: dict_keys(['name'.'price'.'author'])
In [161] :Get all values in the dictionary
In [162]: goods_dict.values()
Out[162]: dict_values(['Gold Digger Booklet XX'.19.9.'hui'])
In [163] :# all key-value pairs in the dictionary (tuple list)
In [164]: goods_dict.items()
Out[164]: dict_items([('name'.'Gold Digger Booklet XX'), ('price'.19.9), ('author'.'hui')])
Copy the code
Dictionary loop through
- Traversal is to get all the key-value pairs in turn from the dictionary
In [167] :for key ingoods_dict: ... :print('key', key) ... :print('value', goods_dict[key]) ... :print(a)... :... : Key name value xx Key Price value19.9
key author
value hui
Copy the code
for … in … By default, all keys in the dictionary keys() are taken, and then values are obtained by keys.
However, we can iterate through the keys and values once through items() in the dictionary
In [168] :for key, value ingoods_dict.items(): ... :print(key, value) ... :print(a)... :... : Name Gold nuggets booklet XX Price19.9
author hui
Copy the code
Application scenarios
- Although it can be used
for in
traverseThe dictionary - However, in development, more application scenarios are:
- Use multiple key-value pairs to store information that describes an object — more complex data information
- Put multiple dictionaries in a list and iterate, doing the same for each dictionary inside the body of the loop
info_list = [
{
"name": "hui"."qq": "222815"."phone": "10010"
},
{
"name": "zack"."qq": "54321"."phone": "10086"
},
{
"name": "wang"."qq": "12345"."phone": "10000"}]Copy the code
The tail language
✍ Code writes the world and makes life more interesting. ❤ ️
✍ thousands of rivers and mountains always love, ✍ go again. ❤ ️
✍ code word is not easy, but also hope you heroes support. ❤ ️