dict

create a dictionary

In [1]:
d1 = {'1':1, '2':2, '3':3, '4' : 4, '5':5, '6':7, '8':8, '9':9, '0':0 }
d2 = dict()

print('d1 : ', d1)
print('d2 : ', d2)

print('d1["3"] : ', d1["3"])
print('d2.get("3") : ', d2.get('3'))
print('d2.get("3") : ', d2.get('3', 0))
print()
d1 :  {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 7, '8': 8, '9': 9, '0': 0}
d2 :  {}
d1["3"] :  3
d2.get("3") :  None
d2.get("3") :  0

In [3]:
# 使用一个二元组的列表创建dict, 二元组中的第一个用于key, 第二个作为value
# 作为key的对象需要是可哈希的不可变对象
t1 = [('a', 1), ('b',2), ('c', 3)]
d3 = dict(t1)
print(d3)


# 使用dict()结合zip()创建dict对象
d4 = dict( zip('123', range(1,4)) )
print(d4)

t2 = ['one', 'two', 'three']
t3 = [i for i in range(1,4)]
print( dict(zip(t2, t3)) )
print( dict(zip(t3, t2)) )
{'a': 1, 'b': 2, 'c': 3}
{'1': 1, '2': 2, '3': 3}
{'one': 1, 'two': 2, 'three': 3}
{1: 'one', 2: 'two', 3: 'three'}

traversing a dictionary

In [8]:
for c, k in d1.items():
    print(c, k)
1 1
2 2
3 3
4 4
5 5
6 7
8 8
9 9
0 0