How to use a Python dictionary?

前端 未结 7 1042
闹比i
闹比i 2020-12-11 21:24

I am finding it difficult to iterate through a dictionary in python.

I have already finished learning via CodeAcademy and solo learn but still find it tough to go th

相关标签:
7条回答
  • 2020-12-11 22:00

    Its irony, although you are looking for alternative resources but trust me no documentation or reference book can beat the official Python documentation as it is always the latest and closest to the python language.

    Browse through different versions on the main python website.

    Dictionary : https://docs.python.org/3/tutorial/datastructures.html#dictionaries

    Here is one more website that has lot of Python resources (even for specific occupations) but as I told before nothing can beat official Python documentation.

    One more link : python wiki.

    Understanding dictionary, below is from official python documentation website ...

    ## dictionary initialization
    >>> tel = {'jack': 4098, 'sape': 4139}
    
    ## set value for a key (either existing or new)
    >>> tel['guido'] = 4127
    
    ## print dictionary
    >>> tel
    {'sape': 4139, 'guido': 4127, 'jack': 4098}
    
    ## get value for an existing key
    >>> tel['jack']
    4098
    
    ## delete a key from dictionary
    >>> del tel['sape']
    
    ## add a new key with value
    >>> tel['irv'] = 4127
    
    ## print dictionary
    >>> tel
    {'guido': 4127, 'irv': 4127, 'jack': 4098}
    
    ## get all keys in dictionary
    >>> list(tel.keys())
    ['irv', 'guido', 'jack']
    
    ## get all keys in dictionary (sorted)
    >>> sorted(tel.keys())
    ['guido', 'irv', 'jack']
    
    ## check if a key exists in dictionary
    >>> 'guido' in tel
    True
    
    ## check if a key exists in dictionary
    >>> 'jack' not in tel
    False
    
    ## Finally iterating thru dictionary
    for key, value in tel.items():
        print(key, value)
    
    0 讨论(0)
提交回复
热议问题