Python Basics: Dictionaries
1 post
Page 1 of 1
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.
Accessing a Dictionary value is done by referencing its associated key:
Much like Lists, Dictionaries in Python can be created using loops and conditionnal statements, for example:
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
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.d = {"key1": 42, "key2": "a string"}
Accessing a Dictionary value is done by referencing its associated key:
Code: Select all
Modifying a value stored in a Dictionary works in the same way:
d = {"key1": 42, "key2": "a string"}
print(d["key2"]) #Prints out "a string"
Code: Select all
Dictionaries, Lists and Tuples are also iterable, which means you can go over them with a for loop:
d = {"key1": 42, "key2": "a string"}
d["key1] += 1 #Increments 42 by 1, becoming 43
Code: Select all
Dictionary comprehensiond = {"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)
Much like Lists, Dictionaries in Python can be created using loops and conditionnal statements, for example:
Code: Select all
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:
my_list = ["programming", "alphabet", "anticonstitutionnal", "python", "potato"]
my_dictionary = {itemkey: len(itemkey) for i in my_list if len(i) <= 5}
Code: Select all
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;{"python": 5, "potato": 5}
1 post
Page 1 of 1
Copyright Information
Copyright © Codenstuff.com 2020 - 2023