python中访问字典

 

1、

>>> a = dict(a = 111, b = 222, c = 333, d = 444)
>>> a["a"]
111
>>> a["c"]
333
>>> b = ("b","d")
>>> for i in b:
    print(a[i])

    
222
444

 

2、

>>> a = dict(zip(("a","b","c","d"),(111,222,333,444)))
>>> a
{'a': 111, 'b': 222, 'c': 333, 'd': 444}
>>> a.get("a")    ## 访问值
111
>>> a.get("d")
444
>>> a.get("e")
>>> a.get("a","none")   ## 设定存在是返回的值
111
>>> a.get("e","none")
'none'

 

3、

>>> a = dict((("a",111),("b",222),("c",333),("d",444)))
>>> a
{'a': 111, 'b': 222, 'c': 333, 'd': 444}
>>> a.keys()   ## 访问键
dict_keys(['a', 'b', 'c', 'd'])
>>> a.values()   ## 访问值
dict_values([111, 222, 333, 444])
>>> a.items()    ## 访问项
dict_items([('a', 111), ('b', 222), ('c', 333), ('d', 444)])

 

posted @ 2021-02-25 21:39  小鲨鱼2018  阅读(157)  评论(0编辑  收藏  举报