• Top Members
    Reps
    Posts
  • 834 Replies
    2585 Replies
  • 716 Replies
    2025 Replies
  • 331 Replies
    1928 Replies

Python Basics: Dictionaries

User avatar
comathi
Coding God
Posts: 1242

Python Basics: Dictionaries

Wed Mar 19, 2014 12:12 am

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;

Post Reply

Return to “Tutorials”