Explanation of python Using Function to Create Dictionary

  • 2021-11-13 08:29:04
  • OfStack

1. Use the dict () function to create a dictionary through other mappings (such as other dictionaries) or a sequence of key and 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)])    #  Dictionary can be constructed by iterating objects 
print(dict3)

2. Use fromkeys () function, which is only used to create a new dictionary, not to save it.

When calling fromkeys method through 1 dictionary, remember to copy it to other variables if you need to use 1 later.


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

Instance extension:

Code: Dictionary Sample


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.
# I feel that the code in the book is rather cumbersome, beginners may look more difficult, re-write a relatively simple version for reference. 


Related articles: