1.创建字典
empty_dict={}
a_dict={'one':1,'two':2,'three':3}
print("{}".format(a_dict))
print("a_dict has {!s} elements".format(len(a_dict)))
another_dict={'x':'printer','y':5,'z':['star','circle',9]}
print("{}".format(another_dict))
print("another_dict also has {!s} elements".format(len(another_dict)))
#结果
{'one': 1, 'two': 2, 'three': 3}
a_dict has 3 elements
{'x': 'printer', 'y': 5, 'z': ['star', 'circle', 9]}
another_dict also has 3 elements
2.引用字典中的值
a_dict={'one':1,'two':2,'three':3}
another_dict={'x':'printer','y':5,'z':['star','circle',9]}
print("{}".format(a_dict['two']))
print("{}".format(another_dict['z']))
#结果
2
['star', 'circle', 9]
3.复制
a_dict={'one':1,'two':2,'three':3}
a_new_dict=a_dict.copy()
print("{}".format(a_new_dict))
#结果
{'one': 1, 'two': 2, 'three': 3}
4.键-值-项目
a_dict={'one':1,'two':2,'three':3}
print("{}".format(a_dict.keys()))
a_dict_keys=a_dict.keys()
print("{}".format(a_dict_keys))
print("{}".format(a_dict.values))
print("{}".format(a_dict.items))
#结果
dict_keys(['one', 'two', 'three'])
dict_keys(['one', 'two', 'three'])
<built-in method values of dict object at 0x000001DA91EE8980>
<built-in method items of dict object at 0x000001DA91EE8980>
5.使用in,not in,get
a_dict={'one':1,'two':2,'three':3}
another_dict={'x':'printer','y':5,'z':['star','circle',9]}
if 'y' in another_dict:
print("y is a key in another_dict:{}".format(another_dict.keys()))
if 'c' not in another_dict:
print("c is not a key in another_dict:{}".format(another_dict.keys()))
print("{!s}".format(a_dict.get('three')))
print("{!s}".format(a_dict.get('four'))) #不存在的键返回None,
print("{!s}".format(a_dict.get('four','Not in dict'))) #键four不存在时返回:Not in dict
#结果
y is a key in another_dict:dict_keys(['x', 'y', 'z'])
c is not a key in another_dict:dict_keys(['x', 'y', 'z'])
3
None
Not in dict
6.排序
#使用sorted()对字典进行排序
a_dict={'one':1,'two':2,'three':3}
print("{}".format(a_dict))
dict_copy=a_dict.copy()
ordered_dict1=sorted(dict_copy.items,key=lambda item: item[0]) #根据键升序
print("order by keys:{}".format(ordered_dict1))
ordered_dict2=sorted(dict_copy.items(),key=lambda item: item[1]) #根据values升序
print("order by values:{}".format(ordered_dict2))
ordered_dict3=sorted(dict_copy.items(),key=lambda x: x[1],reverse=True) #根据value降序
print("order by values,descending:{}".format(ordered_dict3))
ordered_dict4=sorted(dict_copy.items(),key=lambda x: x[1],reverse=False)#根据value升序
print("order by values,ascending:{}".format(ordered_dict4))
#结果
{'one': 1, 'two': 2, 'three': 3}
order by keys:[('one', 1), ('three', 3), ('two', 2)]
order by values:[('one', 1), ('two', 2), ('three', 3)]
order by values,descending:[('three', 3), ('two', 2), ('one', 1)]
order by values,ascending:[('one', 1), ('two', 2), ('three', 3)]
7.总结
(1).不能在列表中给没有的位置赋值。
(2).可以给字典随时创建新的位置。
(3).字典索引不一定是数值,列表的索引是数值。
(4).python使用缩进表示逻辑上一个块。
(5).lambda 函数中 item:item[0],x:x[0],可以替换为任意变量表示。如:y:y[0]在字典中都代表键 ,y:y[1] 有1代表值。