Python Basics: Dictionaries

1 post Page 1 of 1
Contributors
User avatar
comathi
Coding God
Coding God
Posts: 1242
Joined: Fri Mar 26, 2010 1:59 pm

Python Basics: Dictionaries
comathi
Welcome to the third tutorial on Python data types in my "Python Basics" tutorials series. This time, we're going to talk about Dictionaries. These are unordered pairs of keys and values (in comparison, Lists are ordered sequences), which means you cannot access an item by its index (as it doesn't have one), but rather its key.

Creating a Dictionary
Creating a Python Dictionary is as simple as surrounding a comma-seperated list of "key": value pairs with curly braces ("{}") <-- No, that is not some sort of weird smiley lol.
Code: Select all
d = {"key1": 42, "key2": "a string"}
Dictionaries may contain any time of object for values, but the keys must be Strings. Furthermore, like Lists and Tuples, Dictionaries can contain other Dictionaries.

Accessing a Dictionary value is done by referencing its associated key:
Code: Select all
d = {"key1": 42, "key2": "a string"}

print(d["key2"]) #Prints out "a string"
Modifying a value stored in a Dictionary works in the same way:
Code: Select all
d = {"key1": 42, "key2": "a string"}

d["key1] += 1 #Increments 42 by 1, becoming 43
Dictionaries, Lists and Tuples are also iterable, which means you can go over them with a for loop:
Code: Select all
d = {"key1": 42, "key2": "a string"}

for key, value in d.items():
>>>>print(key, value)

for value in d.values():
>>>>print value

for key in d.keys():
>>>>print(key)
Dictionary comprehension
Much like Lists, Dictionaries in Python can be created using loops and conditionnal statements, for example:
Code: Select all
my_list = ["programming", "alphabet", "anticonstitutionnal", "python", "potato"]

my_dictionary = {itemkey: len(itemkey) for i in my_list if len(i) <= 5}
The code above might be a bit complicated, but what it does is simple: It creates a dictionary, my_dictionary with key, value pairs that represent the items in my_list whose length is less than or equal to 5, as well as their length itself. In this case, my_dictionary would be equal to this:
Code: Select all
{"python": 5, "potato": 5}
Well, that's the basic stuff you need to know about Dictionaries in Python. Be sure to check out Python's official documentation on Dictionaries for more cool functions and things to do with Dictionaries. And as always, go crazy! cooll;
1 post Page 1 of 1
Return to “Tutorials”