字典常用操作
import json
d = {"name":"zz","age":"100"}
print(type(d)) # <class 'dict'>
s = json.dumps(d) # 字典转字符串
print(s) # {"name": "zz", "age": "100"}
print(type(s)) # <class 'str'>
dic = json.loads(s) # 字符串转字典
print(dic) # {'name': 'zz', 'age': '100'}
print(type(dic)) # <class 'dict'>
字典排序
# 按出现次数降序排序
# sorted(letter_counts.items(), key=lambda item: item[1], reverse=True) 根据字典的值降序排序
# sorted(letter_counts.items(), key=lambda item: item[0], reverse=True) 根据字典的键降序排序
在字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave