Log in to save your progress.
<< Previous
Home
Next >>
Note! The window is too narrow to use Pythonlab.dev. Use a device with a keyboard!

Reference

Click on a function to read more.
Basics part 1
Syntax
Short description
break
break interrupts code that is repeated
continue
continue interrupts a repetition and starts the next
elif
elif is a combination of else and if
else
else can be used last in an if-statement
float()
Converts to type float (decimal number)
if
if controls the code to do different things depending on a condition
input()
Receives input from the user
int()
Converts to type int (integer)
randint()
Generates a random integer
round()
Rounds a number
str()
Converts to type string
while
while is used to repeat code
Basics part 2
Syntax
Short description
abs
Absolute value
append
Adds an element to a list
def
Defines a function
for
for is used to repeat code
len
Returns the number of elements in an object
max
Returns the largest element
min
Returns the smallest element
pop
Removes an element from a list
return
Returns data from a function
sum
Sums the elements in an object

Lexicon or "dictionary"

In this section you will learn to

What is a dictionary?

A lexicon (English: dictionary) consists of keys and values. Each key has a value. A key must be unique while a value can appear multiple times in the same dictionary. Keys are used to access the value associated with that key.

Because Python uses something called hashing, it is fast to retrieve a value when we have the key. No search is needed. In principle, even if a dictionary is very large, it does not take longer to find a value. That is the big advantage of dictionaries.

Common types for keys are numbers and strings, but it also works to have, for example, tuples as keys. It is possible to have all kinds of objects that are immutable. Lists therefore do not work as keys. As a value, however, lists or any other type work well.

Create a dictionary

It is possible to create a dictionary on one line with the syntax

dictionary = {key_1: value_1, key_2: value_2, ...}

To then read, for example, value_1, we can write dictionary[key_1].

Example

A dictionary with the prices of different fruits. For clarity, each element is written on its own line. Note that two different fruits can have the same price.

prices = {
    'apples': 29, 
    'bananas': 24, 
    'oranges': 19, 
    'grapes': 29
}
banana_price = prices['bananas']
  

It is also possible to first create an empty dictionary with dict() or {} and then add key-value pairs one by one.

Example

Add elements to an initially empty dictionary. The keys are university cities and values are the number of students.

studenter = dict()
studenter['Lund'] = 32036
studenter['Uppsala'] = 35556
studenter['Stockholm'] = 37484
  

If we write a value to a key that already exists in our dictionary, the value is overwritten. To see how many key-value pairs there are in a dictionary, len() can be used.

Example

We see that the number of elements in a dictionary remains the same if we write to an existing key.

favorite_food = {
    'Emil': 'Sushi',
    'Leo': 'Hamburger',
    'Tanja': 'Pizza'
}
element_1 = len(favorite_food) # 3 elements

#changes the value for an existing key
favorite_food['Tanja'] = 'Corn Flakes'
element_2 = len(favorite_food) # 3 elements

#adds a new key-value pair
favorite_food['Christine'] = 'Popcorn'
element_3 = len(favorite_food) # 4 elements

Login or create an account to save your progress and your code.

What does the code do?

Read the code below and try to figure out what the program prints. Run the program after you answer and see if you were correct.

-- Output from your program will be here --

Question: What will the program print?

2
12
12.5
15

Using dictionaries

As we saw earlier, a value can be read by writing dictionary[key]. If the key does not exist in the dictionary, the program will throw an error.

Example with error

Test the code to see what error occurs when a non-existent key is used.

dictionary = dict()
print(dictionary['key_that_does_not_exist'])
  

We can check if the key exists with if key in dictionary:. It is generally very fast to see if a key exists or not, and it takes the same short time even if the dictionary is very large. This can be compared to instead having a list of keys, where it takes much longer to see if the key exists in a large list compared to a small list. (Advanced: In a list twice as large, it takes twice as long to search for a value. In a dictionary, the time is independent of the size.)

Example

If the key exists in the list, we print the value, otherwise we inform that the key does not exist.

millions_inhabitants = {
    'Sweden':10.4,
    'Denmark':5.8,
    'Norway':5.4,
    'Finland':5.5
}
key = input('Enter country.')

if key in millions_inhabitants:
    print(key, millions_inhabitants[key])
else:
    print(key, 'is not in the registry.')
  

It is easy to remove elements from a dictionary. This is done with dictionary.pop(key).

Example

Remove a key-value pair from a dictionary.

user = {
    'id': 2814,
    'name': 'Darth Vader',
    'personality': 'evil'
  }

user.pop('personality')
  

Login or create an account to save your progress and your code.

Change the code

A couple of errors have crept into persondata. The following things must be changed:

  • Add one year to the age.
  • Change the status of children to True.
  • Add English last in the list of languages.
  • In addition, Emil does not like horoscopes so remove the key zodiac_sign from the dictionary.

The program should not print more than what is already printed on line 10.

Note that it is not possible to change lines 1-8. Add code below line 11.

-- Output from your program will be here --

Iterate over a dictionary

A dictionary can be iterated over by iterating over all keys and by iterating over all values.

To iterate over all keys, we write for key in dictionary:, where key is a variable that in turn contains key by key through the loop.

Example

Iterate over the keys in a dictionary.

grand_slams = {
    'Court': 24,
    'Williams': 23,
    'Graf': 22,
    'Federer': 20,
    'Nadal': 20,
    'Djokovic': 20
  }

for spelare in grand_slams:
    print(spelare, 'har', grand_slams[spelare], 'Grand Slam segrar.')
  

To iterate over the values in a dictionary, we can use the function dictionary.values() which returns a list of all values.

Example

Iterate over the values in a dictionary.

grand_slams = {
    'Court': 24,
    'Williams': 23,
    'Graf': 22,
    'Federer': 20,
    'Nadal': 20,
    'Djokovic': 20
  }

for wins in grand_slams.values():
    print('Number of victories', wins)

Login or create an account to save your progress and your code.

Create

Ant Myra lives at coordinate (0,0). Sometimes she wanders to another coordinate and then home again. She always travels parallel to the x and y axes. She has collected which coordinates she has visited and how many times she has visited them in a dictionary. An element like (3,2): 35 means that Myra visited coordinate (3,2) 35 times. Now Myra wants to know which coordinate she has spent the most time going back and forth to. She always walks at the same speed. To coordinate (3,2), Myra has walked the distance 35*(2+3)*2 back and forth. Print the correct coordinate in the form (x,y).

-- Output from your program will be here --
Status
You have finished all tasks in this section!
🎉