标签:
代码:
1
2
|
x = { "a" : "1" , "b" : "2" } print x |
输出:
{‘a‘: ‘1‘, ‘b‘: ‘2‘}
代码:
1
2
|
x = dict (a = "1" , b = "2" ) print x |
输出:
{‘a‘: ‘1‘, ‘b‘: ‘2‘}
代码:
1
2
|
x = dict ((( "a" , "1" ), ( "b" , "2" ))) print x |
输出
{‘a‘: ‘1‘, ‘b‘: ‘2‘}
代码:
1
2
|
x = dict (([ "a" , "1" ], [ "b" , "2" ])) print x |
输出:
{‘a‘: ‘1‘, ‘b‘: ‘2‘}
代码:
1
2
|
x = dict ([( "a" , "1" ),( "b" , "2" )]) print x |
输出:
{‘a‘: ‘1‘, ‘b‘: ‘2‘}
代码:
1
2
|
x = dict ([[ "a" , "1" ],[ "b" , "2" ]]) print x |
输出:
{‘a‘: ‘1‘, ‘b‘: ‘2‘}
注意:
对于a="1"的方式初始化字典,字典的key只能为字符串,并且字符串不用加引号
对于dict内置函数初始化当入参是一个元组时,例如1)、2),元组内部的两元素元组或者列表至少为两个,否则会出错
代码:
1
2
|
dict .fromkeys(( "a" , "b" ), 1 ) print x |
输出:
{‘a‘: 1, ‘b‘: 1}
入参可以的第一个参数是一个列表或者元组,里边的值为key,第二个参数是所有key的value值
标签:
原文地址:http://www.cnblogs.com/hester/p/5153550.html