字典的初始化 In [ 5 ]: a = dict ( one = 1 , two = 2 , three = 3 ) In [ 6 ]: b = { 'one' : 1 , 'two' : 2 , 'three' : 3 } In [ 7 ]: a Out [ 7 ]: { 'one' : 1 , 'three' : 3 , 'two' : 2 } In [ 8 ]: b Out [ 8 ]: { 'one' : 1 , 'three' : 3 ,
- 字典的初始化
In [6]: b = {'one':1, 'two':2, 'three':3}
In [7]: a
Out[7]: {'one': 1, 'three': 3, 'two': 2}
In [8]: b
Out[8]: {'one': 1, 'three': 3, 'two': 2}dictNum = dict(enumerate([0] * 10, 0)) # int:int{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}dictNum[0] += 1{0: 1, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
- 字典排序
#对字典按键排序,用元组列表的形式返回
d1 = sorted(d.items(), key=lambda d:d[0],reverse = False) #[('no', 2), ('ok', 1)]
#对字典按值排序,用元组列表的形式返回
d2 = sorted(d.items(), key=lambda d:d[1],reverse = True) #[('ok', 1), ('no', 2)]
print d1,'\n',d2In [10]: DIAL_CODES = [
...: (86, 'China'),
...: (91, 'India'),
...: (1, 'US'),
...: (62, 'Indonesia'),
...: (55, 'Brazil'),
...: (92, 'Pakistan'),
...: (880, 'Bangladesh'),
...: (234, 'Nigeria'),
...: (7, 'Russia'),
...: (81, 'Japan'),
...: ]
In [11]: country_code = {country:code for code, country in
...: DIAL_CODES}
In [12]: country_code
Out[12]:
{'Bangladesh': 880,
'Brazil': 55,
'China': 86,
'India': 91,
'Indonesia': 62,
'Japan': 81,
'Nigeria': 234,
'Pakistan': 92,
'Russia': 7,
'US': 1}
In [13]: {code:country.upper() for country, code in country
...: _code.items() if code < 66}
Out[13]: {1: 'US', 7: 'RUSSIA', 55: 'BRAZIL', 62: 'INDONESIA'}