Dictionary

Dictionary Basics

All of the compound data types we have studied in detail so far — strings, lists, and tuples — are sequential collections. This means that the items in the collection are ordered from left to right and they use integers as indices to access the values they contain. They are ordered set of data.

Dictionaries are a different kind of collection. It is Python's built-in mapping type. A map is an unordered, associative collection.

You can view dictionary as an unordered set of a comma-separated list of key:value pairs within the braces {}:

dict = { key1: value1, key2: value2...}

Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. And within a single dictionary, the values don't all need to be the same type; you can mix and match as needed.

Dictionary keys are more restricted, which can be any immutable type; strings and numbers can always be keys.

Some Notes:

  • Keys are unique, no duplicate keys in a dictionary
  • Dictionaries have no concept of order among elements
  • Dictionaries are indexed by keys using dict[key], we can access key value this way.

  • Like lists, dictionaries are mutable, we can add new key:value pairs or change key's value

Assign value to a key

dict[key] = value

add new element to the dict if the key was not in original dict

replaces the old value with a new value if assigning a value to an existing key

Example:

dict = {'a':3, 'b': 5, 'c': 8}

# access value by key
print( dict['b'] )        # 5 

# assign new value
dict['b'] = 10
print( dict['b']) )       # 10 (existing key's value changed)

# add new element
dict['add'] = 15
print( dict )          # {'a':3, 'b':10, 'c':8, 'add':15} (a new key:value pair is added, the order of elements may change)

Some functions that work on dictionary:

len(dict) reports the number of key/value pairs in a dictionary

del(dict[key]), delete key:value pair

in and not in keywords, check membership

Examples

fruits = { 'apple' : 2, 'banana' : 1, 'pear' : 6}
print( 'pear' in fruits )      # True

if 'kiwi' not in fruits:
    fruits['kiwi'] = 0

print( fruits )                # {'banaba':1, 'apple':2, 'pear': 6, 'kiwi':0}

fruits['kiwi'] += 10 
del(fruits['pear'])

print( fruits )            # {'banaba':8, 'apple':2, 'kiwi':10}
print( len(fruits) )       # 3

Some useful dictionary methods:**

((not need??

d.keys() returns a view of the keys of d d.values() returns a view of the values of d list(d.keys()) returns a list of all the keys used in the dictionary, in arbitrary order

sorted(d.keys()) will sort the keys in order

))

d.pop(key) removes key and returns its corresponding value d.clear() removes all items from d

Continue with fruits dictionary example:

fruits.pop('apple')
print(fruits)        # {'banaba':8, 'kiwi':10}

fruits.clear()  
print(fruits)        # { }  (empty dictionary)

results matching ""

    No results matching ""