Python Dictionary

published on: | by cindy In category: Python

A dictionary is an unordered collection of key-value pair objects separated by commas. A 'collection' means more than one value can be stored in a single variable. The key must be unique and of an immutable data type such as strings, numbers, or tuples. Values, on the other hand, can be of any type and don't have to be unique.

The general syntax of a dictionary is key-value pair enclosed in curly braces. The key is separated from the value using a colon (:)

variable = {"key1":"value1", "key2":"value2", ...}
# Create a dictionary to store favourite pets
fav_pets = {'dog': "terrier", 'birds': 'parrot'}

Dictionaries just like lists are mutable meaning its values can be altered. The order of items inside a dictionary is unpredictable. You access the value using its key. For ordered collections that do have implicit position slike lists, you use the index to get their values.

Achiengbytes

a dictionary is a memory-based key-value store. The concept of dictionaries in python is the equivalent of associative arrays like Php, Perl just to mention a few. Dictionary keys have no natural order and are always listed in arbitrary order. it uses a hash technique to implement a fast lookup

Add new key-value pair

you can add a new key-value pair to an existing dictionary the dictionary name immediately followed by square brackets with the values you want to add

# create a dictionary of my favourite animals
fav_pets = {'dog': "terrier", 'bird': 'parrot'}

# add snake to the list
snake = fav_pets['snake'] =  'Cobra'

# display the results
print(snake)
print(fav_pets)

Modify Dictionaries values

# Modifying values in a dictionary
# create a ditionary of my favorite animals
fav_pets = {'dog': "terrier", 'bird': 'parrot'}
print(fav_pets) # {'dog': 'terrier', 'bird': 'parrot'}

# I've changed my mind about Terriers
# I love Maltese now

fav_pets ['dog'] =  'Maltese'
print(fav_pets) # {'dog': 'Maltese', 'bird': 'parrot'}

Value lookup

To access the value associated with an individual key, give the name of the dictionary and then place the key in a set of square brackets. If the key you're asking for is not in the dictionary, an error will occur.

# create a dictionary of my favourite animals
fav_pets = {'dog': "terrier", 'bird': 'parrot'}
# Check the values of the key 'dog
dog = fav_pets["dog"]
print(dog) # 'terrier'

# Check the values of the key 'bird'
bird = fav_pets["bird"]
print(bird) # 'parrot'

# Check the values of a non-existent key 'dog
non_existent = fav_pets["snake"]
print(non_existent) # KeyError: 'snake'

you get key-value Error because the key doesn't exist. Python does not like it when we try to get values that don't exist! It blows up. To avoid the KeyError there are workarounds though.

  1. We can use the in operator to check if the value exists and use if statement to do something or otherwise it doesn't exist.
  2. You can use a for loop
  3. The cleaner way to do it is to use get() method and provide a default value if the key doesn't exist

get(value) method

get() method will return None instead of an error if the key doesn't exist.

# create a ditionary of my favorite animals
fav_pets = {'dog': "terrier", 'bird': 'parrot'}

# Check the values of the key 'dog
dog = fav_pets.get("dog")

# Check the values of a non-existent key 'snake' using get
non_existent = fav_pets.get("snake")

print(fav_pets)
print(dog) # 'terrier'
print(non_existent) # displays None

Note

use get(value. default).Give a default value. If the key exists, returns its value. Otherwise, it returns the default value specified.

Removing Key-Value using del

use del keyword with the name of the dictionary immediately followed by the key in square bracket removes the key with its associated value. The syntax looks like this ' del dict[key]`. Let's delete dog key the fave_pets

# create a dictionary of my favorite animals
fav_pets = {'dog': "terrier", 'bird': 'parrot'}
print("created dictionary ", fav_pets)

# del a key using del keyword
del fav_pets['dog']
print(" after deleting dog ", fav_pets)

you will get a KeyError if you try deleting a key that doesn't exist. You can use a for loop or in to check if the key exists to get rid of the error.

# create a dictionary of my favorite animals
fav_pets = {'dog': "terrier", 'bird': 'parrot'}
print("created dictionary ", fav_pets)

# del a non-exstent key using del keyword
del fav_pets['snake']
print('No snake jusy keyerror',fav_pets) # KeyError: 'snake'

""" prevent KeyError using a for loop
check if the key exists """
if  'snake'  in fav_pets:
del fav_pets['snake']
print('No snake key but no error, yay for a loop!',fav_pets)

""" prevent KeyError using the in operator
to check if the key exist """
if  'dog'  in fav_pets:
del fav_pets['dog']
print(fav_pets)

can I use has_key() method

has_key() method is deprecated in python 3 instead use the in operator. If you're using previous versions of python it looks like this """ prevent KeyError using the has_key() to check if the key exist """ if fav_pets.has_key('dog'): del fav_pets['dog'] print(fav_pets)

Removing Key-value using dict.pop(key[, default])

  • if the key exists in the dictionary then dict.pop() removes the element with the given key from the dictionary and return its value.
  • If the given key doesn’t exist in the dictionary then it returns the given Default value.
  • If the given key doesn’t exist in the dictionary and No Default value is passed to pop() then it will throw KeyError

Difference between del and pop()

pop() returns a value

Looping through a dictionary

objects in a dictionary have no natural order but we can still loop inside it with a for loop. A for loop goes through all the entries in a dictionary can loop through a dictionary in 3 ways, key-value pair, key or value

Looping through all key-value pairs

use dict.items() method which will create a tuple with the dictionary elements

# Store people's favorite programming languages.
programming_languages = {'pristol': 'java', 'cindy': 'python','jose': 'php'}
# Show each person's favorite language.
print(programming_languages.items())
# output dict_items([('pristol', 'java'), ('cindy', 'python'), ('jose', 'php')])

now to a more meaninful illustration

# Store people's favorite programming languages.
programming_languages = {'pristol': 'java', 'cindy': 'python','jose': 'php'}
# Show each person's favorite language.
for name, language in programming_languages.items():
    print(name +  ": "  + language)

Multiple iteration variables

​ python allows for a unique way to loop through the key-value using more than one iterable variable. For each iteration, the 1st variable is the key and the second variable is the corresponding value for that key

programming_languages = {'pristol': 'java', 'cindy': 'python','jose': 'php'}
for k,v in programming_languages.items():
    print()

Looping through all the keys

use dict.keys() method.Creates a list of keys.

# create a ditionary of my favorite animals
fav_pets = {'dog': "terrier", 'bird': 'parrot'}
# use keys() to find the keys within the dict
print(fav_pets.keys())

let's die in a more practical illustration

# Store people's favorite programming languages.
programming_languages = {'pristol': 'java', 'cindy': 'python','jose': 'php'}

# Show each person's name.
for name in programming_languages.keys():
 print(name,programming_languages[name])

Looping through all the values

use dict.values() method o generate a list of values

# create a ditionary of my favorite animals
fav_pets = {'dog': "terrier", 'bird': 'parrot'}
# use values() to find the keys within the dict
print(fav_pets.values())

try this secod illustration as well

# Store people's favorite programming languages.
programming_languages = {'pristol': 'java', 'cindy': 'python','jose': 'php'}

# Show the programming languages using values() method.
for language in programming_languages.values():
    print(language)

Methods for creating a new dict

dict.update()

updates the dictionary with the element from another dict object or from a tuple(an iterable key-value pair).

The dictionary remains unchanged if the update() method is called without passing any parameters. The update() method doesn't return any value, it returns None

dict.copy()

This method returns a shallow copy of the dictionary. It doesn't take any parameters. Returns a shallow copy of the dictionary.

oldict ={}
newdict = oldict.copy()

Counting with Dictionaries

Okay, let us have some fun. The user will write a paragraph long about favourite pets. The data will be split using whitespace, create an empty dictionary using dict() loop through the dictionary and keep count of each word that has been repeated.

data =  input("Enter a paragraph of your avourite pets")
# split the string using whitespace
words = data.split() 
# create an empty dictionary , dict()
counts = {}
# print the split words
print('words:', words)
for word in words:
    counts[word] = counts.get(word, 0)+1
print('counts:', counts)