Example of how to use dict (dictionary) in python3

  • 2020-05-27 05:58:32
  • OfStack

1. clear(empty the dictionary)


stu = {
  'num1':'Tom',
  'num2':'Lucy',
  'num3':'Sam',
}
print(stu.clear())

# Output: None

2. copy (copy the dictionary)


stu = {
  'num1':'Tom',
  'num2':'Lucy',
  'num3':'Sam',
}
stu2 = stu.copy()
print(stu2)

3. fromkeys(specify 1 list, take the values in the list as key of the dictionary, generate 1 dictionary)


name = ['tom','lucy','sam']
print(dict.fromkeys(name))
print(dict.fromkeys(name,25)) # Specify default values 

# Output: {'tom': None, 'lucy': None, 'sam': None}
#   {'tom': 25, 'lucy': 25, 'sam': 25}

4. get(specify key, get the corresponding value)


stu = {
  'num1':'Tom',
  'num2':'Lucy',
  'num3':'Sam',
}
print(stu.get('num2'))

# Output: Lucy

5. items(returns a list of key value pairs)


stu = {
  'num1':'Tom',
  'num2':'Lucy',
  'num3':'Sam',
}
print(stu.items())

# Output: dict_items([('num2', 'Lucy'), ('num3', 'Sam'), ('num1', 'Tom')])

6. keys(get all key of the dictionary)


stu = {
  'num1':'Tom',
  'num2':'Lucy',
  'num3':'Sam',
}
print(stu.keys())

# Output: dict_keys(['num3', 'num1', 'num2'])

7. pop(gets value for key and deletes it from the dictionary)


stu = {
  'num1':'Tom',
  'num2':'Lucy',
  'num3':'Sam',
}
name = stu.pop('num2')
print(name,stu)

# Output: Lucy {'num1': 'Tom', 'num3': 'Sam'}

8. popitem(get a key value pair at random and delete it from the dictionary)


stu = {
  'num1':'Tom',
  'num2':'Lucy',
  'num3':'Sam',
}
name = stu.popitem()
print(name,stu)

# Output: ('num2', 'Lucy') {'num3': 'Sam', 'num1': 'Tom'}

9. setdefault(gets value for the specified key, or creates if key does not exist)


stu = {
  'num1':'Tom',
  'num2':'Lucy',
  'num3':'Sam',
}
name = stu.setdefault('num5')
print(name,stu)

# Output: None {'num1': 'Tom', 'num2': 'Lucy', 'num5': None, 'num3': 'Sam'}

10. update(add key-value pairs to dictionary)


stu = {
  'num1':'Tom',
  'num2':'Lucy',
  'num3':'Sam',
}
stu.update({'num4':'Ben'})
print(stu)

# Output: {'num2': 'Lucy', 'num3': 'Sam', 'num1': 'Tom', 'num4': 'Ben'}

conclusion


Related articles: