Python study notes: examples of using dictionaries

  • 2020-04-02 13:47:12
  • OfStack

Classic dictionaries use functions
Dict: dictionaries are built by other mapping (such as other dictionaries) or sequence pairs (keys, values). Of course, dict is not exactly a function, it is essentially a type. As the list.


items=[('name','zhang'),('age',42)]
d=dict(items)
d['name']

Len (d): returns the number of items
D [k]: returns the value above the key k.
D [k]=v: set the corresponding value of k to k.
Del d[k]: remove this entry from the dictionary.
K in d: check whether d contains an item with a key of k. Note: you can only find keys, not values.
Simple phone book example:


# A simple database
# A dictionary with person names as keys. Each person is represented as
# another dictionary with the keys 'phone' and 'addr' referring to their phone
# number and address, respectively.
people = {
    'Alice': {
        'phone': '2341',
        'addr': 'Foo drive 23'
    },
    'Beth': {
        'phone': '9102',
        'addr': 'Bar street 42'
    },
    'Cecil': {
        'phone': '3158',
        'addr': 'Baz avenue 90'
    }
}
# Descriptive labels for the phone number and address. These will be used
# when printing the output.
labels = {
    'phone': 'phone number',
    'addr': 'address'
}
name = raw_input('Name: ')
# Are we looking for a phone number or an address?
request = raw_input('Phone number (p) or address (a)? ')
# Use the correct key:
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
# Only try to print information if the name is a valid key in
# our dictionary:
if name in people: print "%s's %s is %s." % 
    (name, labels[key], people[name][key])

The dictionary method
Clear: clear all the entries in the dictionary.


x.clear()

-penny: I'm copying the dictionary.


y=x.copy()

Deepcopy: copy again. Let's see the difference.


from copy import deepcopy
d={}
d['names']=['as','sa']
c=d.copy()
dc=deepcopy(d)
d['names'].append('ad')

Fromkeys: creates a new dictionary for the specified keys. Each key has a default value of none.

{}.fromkeys(['name','age'])

Get: a more relaxed way to access dictionary entries.

d.get('name')


# A simple database using get()
# Insert database (people) from Listing 4-1 here.
labels = {
    'phone': 'phone number',
    'addr': 'address'
}
name = raw_input('Name: ')
# Are we looking for a phone number or an address?
request = raw_input('Phone number (p) or address (a)? ')
# Use the correct key:
key = request # In case the request is neither 'p' nor 'a'
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
# Use get to provide default values:
person = people.get(name, {})
label = labels.get(key, key)
result = person.get(key, 'not available')
print "%s's %s is %s." % (name, label, result)

Has_key: checks whether the dictionary contains the given key. D.h. aos_key (). The value returns True,False.

Items: returns a list of all dictionary items.

Iteritems: the method is roughly the same, but returns an iterator instead of a list.

Keys: returns the keys in the dictionary as a list. (notice the difference between items and items)

Iterkeys: returns an iterator for keys.

Pop: gets the value for the given key and then removes the key-value pair.

Popitem: a random item pops up,

Setdefault: the value associated with a given key can be obtained, and the value can be set without the key in the dictionary.

-sheldon: update one dictionary with another.


d={'1':'d','2':'s','3':'a'}
x={'1','jk'}
d.update(x)

Values: returns the values in the dictionary as a list.

Itervalues: returns a worthwhile iterator.


Related articles: