An example of Python creating a dictionary with functions

Time:2022-5-5

1. Use the dict () function to establish a dictionary through other mappings (such as other dictionaries) or sequences of key value pairs.

Dict1 = dict (a ='a ', B ='b', t ='t ') # incoming keyword
print(dict1)
 
Dict2 = dict (ZIP (['one ',' two ',' three '], [1, 2, 3])) # mapping function to construct dictionary
print(dict2)
 
Dict3 = dict ([('one ', 1), ('two', 2), ('three ', 3)]) # the dictionary can be constructed in an iterative object way
print(dict3)

2. The fromkeys () function is only used to create a new dictionary and is not responsible for saving it.

When you call the fromkeys method through a dictionary, if you need to use it later, be sure to copy it to other variables.


dict3 = dict.fromkeys(['name','age'])
print(dict3)
 
dict4 = dict.fromkeys(['name','age'],10)
print(dict4)

Instance extension:

Code: Dictionary example

people = {
    'libai':{'phone':'189','addr':'jiangxi'},'lilei':{'phone':'180','adder':'hunan'},
    'lihong':{'phone':'152','adder':'hubei'},'liming':{'phone':'153','adder':'tianjing'},
    'licheng':{'phone':'154','adder':'beijing'}}
name = input('name:')
if name in people: print("{}'s phone number is {}, address is {}."
.format(name,people[name]['phone'],people[name]['adder']))

#Actual operation
#name:liming
#liming's phone number is 153, address is tianjing.
#Personally, I feel that the code in the book is cumbersome, and beginners may look hard. I wrote a simpler version for reference.

This is the end of this article on how Python uses functions to create dictionaries. For more information on how Python uses functions to create dictionaries, please search previous articles on developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!