Dictionary (dict)

1. (1) key: lists, dictionaries can not be used as keys (bool value can, 0 errors, 1 for right)

   (2) value: the value may be any

2. A dictionary is unordered

3. Value

(1) Index Value: dict [key] >>>>>>>> value, if not in the dictionary dict the key, an error is reported.

(2) get (key): If there are no prints none

(3) .keys (): get all the key

(4) .values ​​(): get all the value

(5) .items (): get the dictionary all key-value pairs for each key is a tuple

b = {"a":3,"b":5}
c=b.items()
print(c)
》》》》
》》》》dict_items([('a', 3), ('b', 5)])

 

4. The loop can be made for

d = {"a":1,"b":2}
for
k ,v in d.items(): print(k,v)

5. You can delete:

(1) .pop (key): Delete the value corresponding to the key, and returns that value.

(2) .popitem (): random delete 

(An element can be deleted when the list can be deleted as one layer, but is in the form of a listing) by deleting the index; (3) del [key]

6. Create a dictionary or add key-value pairs

(1) dict.fromkeys (sequence, a value)

a = dict.fromkeys([1,2,3,4],5)
print(a)
》》》》
》》》{1: 5, 2: 5, 3: 5, 4: 5}

(2).setdefault("a"5)

When "a" exists in the dictionary, is not set, the corresponding value acquired

a = {"a":1,"b":2}
c = a.setdefault("a",5)
print(c)
》》》》
》》》》1

 When "a" does not exist in the dictionary, then added: "a": 5

a = {"c":1,"b":2}
c = a.setdefault("a",5)
print(a)
print(c)
》》》
》》》{'c': 1, 'b': 2, 'a': 5}
》》》5

 7. Update dictionary

.update()

a = {"c":1,"b":2}
b = {"a":3}
a.update(b)
print(a)
>>>
>>>{'c': 1, 'b': 2, 'a': 3}

 

Guess you like

Origin www.cnblogs.com/chenweitao/p/11227555.html