Python Wiki


43pages on
this wiki
Add New Page
Talk0 Share

General Information Edit

Dictionaries is a data type in Python.
This type is closely related to Lists, but it has the key advantage of so-called Keys. That also explains the name, we have a key and the description to it. Furthermore, this can contain several types, but the key has to be a String.
To explain this, we look at the Syntax:

The Syntax Edit

Lets look at a basic example of a Dictionary:

>>> my_dict = { 'Hello' : 'World!', 'other' : 'do not know' }
>>> my_dict['Hello']
>>> my_dict['other']
'do not know'
Please note the structure:
{ keyword : description, ... }

The main advantage here is that we don't have to write something abstract like my_dict[0] as in lists.

Operations on dictionaries Edit

Python let us operate in different ways on dictionaries:

Adding elements Edit

To add a new element, we just call it:

>>> my_dict['forname'] = 'surname'
>>> my_dict
{'Hello' : 'World!', 'other' : 'do not know', 'forname' : 'surname'}

Changing values Edit

To change values/descriptions of already existing entries, we call it again:

>>> my_dict['Hello'] = 'Universe'
>>> my_dict
{'Hello' : 'Universe!', 'other' : 'do not know', 'forname' : 'surname'}

Deleting entries Edit

To delete entries from this structure, we use the widely used del command:

>>> del my_dict['other']
>>> my_dict
{'Hello' : 'World!', 'forname' : 'surname'}

Built-in functions and attributes Edit

keys() Edit

This function list up all keys:

>>> my_dict.keys()

get(KEY) Edit

This function returns the value of the key KEY in the dictionary:

>>> my_dict.get('Hello')

has_key(KEY) Edit

This function returns True, if the key KEY is an element of the dictionary, False if not:

>>> my_dict.has_key('Hello')
>>> my_dict.has_key('Helle')

items() Edit

This function zips up all elements of a dictionary to a list of tupels, where the left side of the tuple is the key and the right one the value:

>>> my_dict.items()
[('Hello', 'World!'), ('other', 'do not know'), ('forname', 'surname') ]

pop(KEY) Edit

This well-known function returns the entry with the key KEY from the dictionary and returns this element:

>>> my_dict.pop('other')
'do not know'
>>> my_dict
{'Hello' : 'World!', 'forname' : 'surname'}

values() Edit

This function is the exact opposite of the keys function, so it returns a list of all values:

>>> my_dict.values()
['World!', 'do not know', 'surname']

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.