This article example describes the built-in functions of python tuples and dictionaries. Shared for your reference, as follows:
Tuple
A tuple is a sequence type and an immutable type data structure, and modifications to a tuple generate a new tuple. So Tuple objects don't have many built-in methods.
count() queries the number of an element in a Tuple
count(…)
(value) -> integer – return number of occurrences of value
Returns the number of times a value appears in the Tuple, i.e., the number of individuals.
In [5]: tup = ('My','name','is','Jmilk') In [6]: ('My') Out[6]: 1 In [7]: ('my') Out[7]: 0
index() queries the index number of the element in the Tuple
index(…)
(value, [start, [stop]]) -> integer – return first index of value.
Raises ValueError if the value is not present.
Returns the index of the first occurrence of value in the specified range [start,[stop]].
In [15]: ('Jmilk',2,4) Out[15]: 3
Iteration of tuples
In [16]: tup Out[16]: ('My', 'name', 'is', 'Jmilk') In [17]: for i in tup: ....: print i ....: My name is Jmilk
Dictionary
Dictionary data types use mapping relationships of key-value pairs to associate data.
Creating a Dictionary Object
Simple Creation
In [18]: dic = {'name':'Jmilk','age':23,'city':'BJ'}
fromkey() creates a dictionary using keys
fromkeys(…)
(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
Creates a dictionary from a sequence of keys, you can specify the value that the keys map to, defaults to None.
In [125]: newDic = {}.fromkeys(['name','age','city'],'not found') In [126]: newDic Out[126]: {'age': 'not found', 'city': 'not found', 'name': 'not found'}
consult (a document etc)
Query the value mapped to the key in the dictionary.
In [44]: dic['age'] Out[44]: 23
get() queries the value of the Key mapping, when the key does not exist, return the default value
get(…)
(k[,d]) -> D[k] if k in D, else d. d defaults to None.
Auto-add (dictionary default): auto-add is a feature of the dictionary datatype that allows new items to be created by assigning a value to a Key even if the Key does not initially exist in the dictionary.
In [6]: dic Out[6]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk'} In [7]: ('age',24) Out[7]: 23 In [8]: ('a',24) Out[8]: 24
If you don't use the get() function to get the value of a non-existent key, you will get an error.
len(dictName) get dictionary length
len(…)
len(object) -> integer
Return the number of items of a sequence or mapping.
len() is a built-in function in Python that gets the length of a sequence or dictionary, i.e. the number of elements.
In [34]: len(dic) Out[34]: 3
keys() lists the keys of the dict.
keys(…)
() -> list of D's keys
In [22]: () Out[22]: ['city', 'age', 'name']
values() lists the values of the dict.
values(…)
() -> list of D's values
In [23]: () Out[23]: ['BJ', 23, 'Jmilk']
Adding Dictionary Entries
Adding an item to a dictionary by assignment
Format: dictName[keyN] = valueN
In [25]: dic Out[25]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk'} In [27]: dic['sex'] = 'man' In [28]: dic Out[28]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk', 'sex': 'man'}
Added by setdefault()
setdefault(…)
(k[,d]) -> (k,d), also set D[k]=d if k not in D
When key exists, call (k,d) method, i.e., get the value mapped by the key. when key does not exist, execute D[k]=d, i.e., add a new element to the dict.
In [25]: dic Out[25]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk'} In [26]: ('age',24) Out[26]: 23 In [27]: ('sex','man') Out[27]: 'man' In [28]: dic Out[28]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk', 'sex': 'man'}
Deleting dictionary entries
The del statement removes an item in the dictionary corresponding to the key.
The del statement operates on all iterator objects.
In [40]: dic Out[40]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk'} In [41]: del dic['age'] In [42]: dic Out[42]: {'city': 'BJ', 'name': 'Jmilk'}
popitem() pops a random dictionary key-value pair (deletes and returns it)
popitem(…)
() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
Removes an element of the dictionary as tuple(k,v) and returns it. Requires an object that accepts the return. If the dictionary is empty, an error is reported.
In [32]: dic Out[32]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk', 'sex': 'man'} In [34]: () Out[34]: ('city', 'BJ') In [35]: () Out[35]: ('age', 23)
pop() pops the value of the key mapping
pop(…)
(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
In [39]: dic Out[39]: {'name': 'Jmilk', 'sex': 'man'} In [40]: ('name') Out[40]: 'Jmilk'
In general, the () method is called when the dictionary is empty, which triggers a KeyError, but you can also add a default value to be returned when the key doesn't exist by making the following call.
Returns the default value when the Key does not exist to avoid reporting errors:
In [20]: dic Out[20]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk'} In [21]: ('sex','man') Out[21]: 'man'
clear() clears all items in the dictionary.
clear(…)
() -> None. Remove all items from D.
Empties all items and returns None.
In [58]: dic Out[58]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk'} In [59]: () In [60]: dic Out[60]: {}
modifications
Simple modification of the value of a key mapping in a dict
Format: "`dictName[key] = newValue
In [50]: dic['city'] = 'GZ' In [51]: dic Out[51]: {'age': 23, 'city': 'GZ', 'name': 'Jmilk'}
update() updates the dictionary.
update(…)
([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
Use another dictionary to update a dictionary by matching the key to the value.
In [137]: dic Out[137]: {'age': 23, 'city': 'BJ', 'name': ['jmilk']} In [138]: newInfo = {'name':'chocolate','age':22,'city':'ZH'} In [139]: (newInfo) In [140]: dic Out[140]: {'age': 22, 'city': 'ZH', 'name': 'chocolate'}
Of course, it is possible to update only a number of these values.
Dictionary copying
copy() shallow copy
A shallow copy of a dictionary is similar to a shallow copy of a List, in that both are just copies of referenced objects.
In [107]: dic1 = () In [108]: dic,dic1 Out[108]: ({'age': 23, 'city': 'BJ', 'name': ['jmilk', 'chocolate']}, {'age': 23, 'city': 'BJ', 'name': ['jmilk', 'chocolate']}) In [109]: dic1['age'] = 24 In [110]: dic,dic1 Out[110]: ({'age': 23, 'city': 'BJ', 'name': ['jmilk', 'chocolate']}, {'age': 24, 'city': 'BJ', 'name': ['jmilk', 'chocolate']})
Note: Doing a replace operation (replacing the whole value) on the value in the new dictionary obtained by shallow copy will not affect the meta-dictionary. However, if you do a modification operation on the value in the new dictionary (modifying a part of it), it will affect the original dictionary. As follows:
In [111]: dic1['name'].remove('chocolate') In [112]: dic,dic1 Out[112]: ({'age': 23, 'city': 'BJ', 'name': ['jmilk']}, {'age': 24, 'city': 'BJ', 'name': ['jmilk']})
Because the ids of both keys point to the same data object, a modification (change of data object) to the data object will affect both. However, replacing (changing the referenced object) the entire value, i.e., pointing the id of the key in the new dictionary to another data object, will not change the original data object.
For a detailed description of deep copy and shallow copy, see:https:///article/
type conversion
item() takes each dictionary item and converts it to a mixed data type of Tuple and List.
items(…)
() -> list of D's (key, value) pairs, as 2-tuples
In [42]: dic Out[42]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk'} In [43]: () Out[43]: [('city', 'BJ'), ('age', 23), ('name', 'Jmilk')] In [44]: [x for param in dic for x in dic] #Nested list dimensionality reduction Out[44]: ['city', 'age', 'name', 'city', 'age', 'name', 'city', 'age', 'name']
Because an object of type List is returned, the index operator can be used.
In [46]: ()[0] Out[46]: ('city', 'BJ') In [48]: ()[0][0] Out[48]: 'city'
As you can see, the operations that can be done on an object are largely determined by the type of the object.
Membership
Determine if a kay exists in a dict
In [56]: dic Out[56]: {'age': 23, 'city': 'GZ', 'name': 'Jmilk'} In [57]: dic.has_key('age') Out[57]: True
True ⇒ key exists in dict
False ⇒ key does not exist in dict
Use the membership operator to determine
Membership: 'age' in dic can only be determined by the membership of the key.
In [45]: dic Out[45]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk'} In [46]: 'age' in dic Out[46]: True In [47]: 'age' not in dic Out[47]: False
Dictionary traversal
In [62]: dic Out[62]: {'age': 23, 'city': 'GZ', 'name': 'Jmilk'} In [63]: for key_num,val_num in (): ....: print key_num,val_num ....: city GZ age 23 name Jmilk
Formatting output value
Output the mapped value by formatting %(key)format
In [53]: dic Out[53]: {'age': 23, 'city': 'BJ', 'name': 'Jmilk'} In [54]: print 'ple call me %(name)s,Thx!' % dic ple call me Jmilk,Thx! In [55]: print 'I m %(age)d years old.' % dic I m 23 years old.
Any conversion descriptor can be used as long as key in dict.
Readers interested in more Python related content can check out this site's topic: theSummary of Python function usage tips》、《Python list (list) manipulation techniques summarized》、《Summary of Python dictionary manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope the description of this article will help you in Python programming.