Dictionary operations for basic python tutorials

  • 2020-04-02 13:30:22
  • OfStack

The dictionary
The dictionary

1. Collection of key-value pairs (map)

2. Dictionaries are collections of data surrounded by braces "{}"

3. Dictionaries are unordered, and members are accessed by keys in dictionaries. Mutable, nested, in place to modify extensions, etc., does not generate new dictionaries

4. The key of the dictionary can be a string (case sensitive), numeric constant or tuple (immutable type), and the key of the same dictionary can be mixed types. The keys of the dictionary must be hashed

The condition for a tuple to be a key is that the values within the tuple are of an immutable type


a = (1,2)  # It can be a bond 
b = (1,2,[3,4])  # Can not be 

5. Dictionary values can be of any type, can be nested, and can be freely modified

The statement
Several ways to create a dictionary:

1. The basic


d = {} # An empty dictionary 
d = {'name':'tom', 'age':22} 
# equivalent 
d = {}
d['name'] = 'tom'
d['age'] = 22

2. The dict


d = dict() # empty 
d = dict(name='tom', age=22)   
d = dict([('name','tom'), ('age',22)])
# equivalent 
keys = ['name','age']
values = ['tom', 22]
d = dict(zip(keys,values))

3. Fromkeys

Default None if default_value is not specified


>>> dict.fromkeys(['name','age'],'default_value')
{'age': 'default_value', 'name': 'default_value'}

Basic operation

Get help


help(dict)

1. Determine if the key exists in the dictionary

if k in d:   #k not in
    dosomething()

2. Read


d = {'a':1, 'b':2}
print d['a']  # get 1 , but if the key does not exist, an exception is thrown KeyError . Use with caution, not recommended 

Print d.get('c', 3) # gets 3,get method, if the key does not exist, return the second parameter, default_value. If there is no default_value, return None
There are three ways to handle missing-key errors, according to specific needs


if k in d:
    print d[k]
try:
    print d[k]
except KeyError:
    dosomething()
print d.get(k, default)
# equivalent  d[k] if k in d else default

3. The traverse

Method 1:


for key in d:
    print key, d[key]
# equivalent  for key in d.keys()

Method 2:


for key,value in d.items():
    print key, value

4. Modify mode 1: a key value pair


d['key'] = 'newvalue'

Mode 2: batch add or update


# Another dictionary 
d.update({'key':'newvalue'})  # A whole set of values is supported here 
# Yuan group list 
d.update( [ ('a',1), ('b',2) ] ) # Two elements per tuple, (key,value)
#**key
d.update(c=3, e=4)

5. Remove


del d['key']
value = d.pop('key') # Deletes and returns the value 
d.clear() # empty 
6. Other: 
len(d)   # The length of the 
d.keys()  #key The list of 
d.values()  #value The list of 
d.items()   #(key, value)  The list of 
c = d.copy()   # Shallow copy 
# Returns the iterator, saving memory 
d.iterkeys()
d.itervalues()
d.iteritems()
d.setdefault('name', 'ken') # If not, set, otherwise the original value will not change 

other
1. Dictionary sort is sorted by key


keys = d.keys()
keys.sort()
for key in keys:
    print d.get(key)

Sort by value


sorted(d.items(), lambda x,y: cmp(x[1],y[1]))

In addition:

# Assuming that d For the dictionary 
sorted(d)  # Return to the same  sorted(d.keys()) , which returns zero key The sorting 

2. Custom object as key

Must:


def __hash__(self):
    pass
def __eq__(self, other):
    pass

3. Shallow copy of dictionary:


c = d.copy() #

The copy module must be used for deep copy

form copy import deepcopy
c = deepcopy(d)

4. One usage scenario assumes a large list l, assuming 10w records

I have a little list b, and I want to know if the elements in b are in l

If:


for i in b:
    if i in l:
        dosomething()

You'll find it's very, very slow... Because the second in statement is going to go through 10w... .

Improvement:


d = dict.fromkeys(l)
for i in b:
    if i in d:
        dosomething()
# Space for time, O(n) -> O(1)


Related articles: