Dictionary (dict) built-in method

Dictionary (dict) built-in method

common

  • Press the key value
    dic [ 'key'] extracted in the key data dictionary
    key is the dictionary must

    dic [ 'key'] = str / int / ... to change the data dictionary into the key behind the content

  • Length (len)
    len (DIC) in the dictionary the number of key

  • in in and not
    Key in dic str whether in the dictionary (the dictionary must be exactly the same in order to return an item Ture)
    Key List Key if not in not in the dictionary, (an item must be exactly the same to the dictionary return False)
    return value is True and False

    It can only be a key, not a key content

  • Delete (del)
    del DIC [ 'key] key to delete the key value and the contents inside, if n is not the attention delete the entire list, that does not exist after the deleted

  • pop (Delete)

The same as del, but you can call directly return data to be deleted

  • keys (key), values ​​(value), items (key-value pairs)

    dic.keys () is withdrawn all key value

    dic.values ​​() is taken for all the contents of the key value

    dic.items () corresponding to the content is extracted and the inside of the key value

    Note that the list of python removed, but is removed python3 tuple.

  • cycle

    for i , j in dic.items():
        print(i , j)

    Each element of the print dictionary

It should be common

  • get (get)

    dic.get (key1) obtained key key1 of value, if the key does not exist return Null

    My understanding is that the press key value is different, even if the key value is not in the dictionary does not error, but the error will press the key value

  • update (Update)
    dic1.update (DIC2) dic1 them to update the DIC2

  • fromkeys (quickly generate a dictionary)

seq = ('Google', 'Runoob', 'Taobao')
dict = dict.fromkeys(seq)
print "新字典为 : %s" %  str(dict)
dict = dict.fromkeys(seq, 10)
print "新字典为 : %s" %  str(dict)

Output:

新字典为 : {'Google': None, 'Taobao': None, 'Runoob': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Runoob': 10}
  • setdefault (add only not modify)
    dict.setdefault ( 'key', str) as key does exist in the dictionary, the key value of the contents will not be any change, if the key value is not in the dictionary, add the key value and str into the dictionary

Guess you like

Origin www.cnblogs.com/marklijian/p/11265756.html