python中创建字典、字典的访问
1、
>>> test1 = {"aaa":111,"bbb":222,"ccc":333} >>> test1 {'aaa': 111, 'bbb': 222, 'ccc': 333} >>> type(test1) <class 'dict'> >>>
2、
>>> test2 = dict((("aaa",111),("bbb",222),("ccc",333))) >>> test2 {'aaa': 111, 'bbb': 222, 'ccc': 333} >>> type(test2) <class 'dict'>
3、
>>> test3 = dict(aaa=100,bbb=200,ccc=300) >>> test3 {'aaa': 100, 'bbb': 200, 'ccc': 300} >>> type(test3) <class 'dict'> >>>
4、
>>> a = ["aaa","bbb","ccc"] >>> b = [100,200,300] >>> test4 = dict(zip(a,b)) >>> test4 {'aaa': 100, 'bbb': 200, 'ccc': 300} >>> type(test4) <class 'dict'>
5、
>>> test5={} >>> test5["aaa"] = 100 >>> test5["bbb"] = 200 >>> test5["ccc"] = 300 >>> test5 {'aaa': 100, 'bbb': 200, 'ccc': 300} >>> type(test5) <class 'dict'>
6、如果键重名,前面的将被后面的覆盖
>>> test1 = {"aaa":100,"bbb":200,"ccc":300,"aaa":400} >>> test1 {'aaa': 400, 'bbb': 200, 'ccc': 300}
7、键、键值、键值对的访问
>>> test1 {'aaa': 400, 'bbb': 200, 'ccc': 300} >>> test1["aaa"] 400 >>> for i in test1: print(i) aaa bbb ccc >>> for i in test1: print(test1[i]) 400 200 300 >>> for i in test1: print(i,":", test1[i]) aaa : 400 bbb : 200 ccc : 300