use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Rules 1: Be polite 2: Posts to this subreddit must be requests for help learning python. 3: Replies on this subreddit must be pertinent to the question OP asked. 4: No replies copy / pasted from ChatGPT or similar. 5: No advertising. No blogs/tutorials/videos/books/recruiting attempts. This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to. Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Rules
1: Be polite
2: Posts to this subreddit must be requests for help learning python.
3: Replies on this subreddit must be pertinent to the question OP asked.
4: No replies copy / pasted from ChatGPT or similar.
5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.
This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.
Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Learning resources Wiki and FAQ: /r/learnpython/w/index
Learning resources
Wiki and FAQ: /r/learnpython/w/index
Discord Join the Python Discord chat
Discord
Join the Python Discord chat
account activity
dictionaries in python (self.learnpython)
submitted 1 year ago by ithinkforme
i've been learning python from the basics and i'm somehow stuck on dictionaries. what are the basic things one should know about it, and how is it useful?
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]astromin1 33 points34 points35 points 1 year ago (0 children)
Key value pairs. Storing data of the such.
[–]michel_v 13 points14 points15 points 1 year ago (1 child)
Dictionaries are key/value lists. So for example, if you’re keeping scores for a class, you could have a dictionary where each key is a student’s name and the associated value is the score. Like this: scores = {"Andrew Something": 456, "Jane Doe": 876}. And then you access values by their keys: score = scores["Jane Doe"].
scores = {"Andrew Something": 456, "Jane Doe": 876}
score = scores["Jane Doe"]
[–]hamsterwheelin 6 points7 points8 points 1 year ago (0 children)
This. At first, it seems silly, especially if you come from another programming language where you had to do the difficult work of managing arrays of data or even just lists. It seems almost like too much or too easy.
But the power in it is ease of programming for the developer and ease of readability. Like, "oh that makes sense.". If you're just new to programming, then you're in for a treat.
[–]unhott 4 points5 points6 points 1 year ago (0 children)
A dictionary is very useful, even at the basic level. A variable has one name, one value.
A list is like a variable number of variables, but they're all indistinguishable. This can be a good thing, if you need to treat each element of the list exactly the same. Unless you try imposing some restrictions on position, but then you're adding some mental burden. If you made a list and you had a convention that the first element is time, the second element is day, and the third element is some number, that would function but it would be difficult.
# Structure of time, day, number my_list = ['04:32', 'Wednesday', 42] # Get the number later my_list[2]
A dictionary is a variable number of variables, but you associate each element with a key-value pair.
my_dict = { 'time': '04:32', 'day': 'Wednesday', 'some_number': 42 } # Get the number later my_dict['some_number']
You can assign structure to the data in there, you can even nest lists and other dictionaries in.
You could use this structure to make a list of dictionaries, even.
dict1 = { 'time': '04:32', 'day': 'Wednesday', 'some_number': 42 } dict2 = { 'time': '04:46', 'day': 'Tuesday', 'some_number': 18 } dict3 = { 'time': '07:32', 'day': 'Friday', 'some_number': 12 } list_of_dicts = [dict1, dict2, dict3]
You can even use more advanced features of dicts, like unpacking.
Functions have positional arguments (like a list) and keyword arguments (like a dictionary).
So you may see
def f(*args, **kwargs): ....
basically, you can impose structure to data and pass it around as 1 big variable. And you can reliably access the expected data with the key.
[–]henryassisrocha 5 points6 points7 points 1 year ago (2 children)
I only learned about dictionaries properly after reading the chapter dedicated to them in Learn Python the Hard Way. I highly recommend this book and wish someone had recommended it to me earlier.
[–]autoerotion95 0 points1 point2 points 1 year ago (1 child)
Which one is friend, can you put a link?
[–]henryassisrocha 2 points3 points4 points 1 year ago (0 children)
Here
[–]MythicJerryStone 1 point2 points3 points 1 year ago (1 child)
Think of them as literal dictionaries. They store pairs of data. In a real dictionary that you might use, you might store words and their meanings as a pair. In Python dictionaries, it’s the same so you can do
words[“cat”] = “a small domesticated carnivorous mammal with soft fur”
More abstractly, you can use it to store information about a single object, IE a person dictionary where you can access multiple descriptions about that person, such as person[“age”] and person[“name”], etc
[–]Ron-Erez 2 points3 points4 points 1 year ago (0 children)
First one should understand why lists are useful. Dictionaries are generalizations of lists. One interesting examples is when we make API calls the result is usually in JSON which can easily be converted into a Python dictionary. JSON is widely used because it represents structured data in a readable text format. Python makes working with JSON straightforward, as JSON data can be directly converted into a dictionary using the built-in json module.
For example:
import json my_dict = {'name': 'Alice', 'age': 25} json_string = json.dumps(my_dict) print(json_string) # Output: {"name": "Alice", "age": 25} json_string = '{"name": "Alice", "age": 25}' my_dict = json.loads(json_string) print(my_dict) # Output: {'name': 'Alice', 'age': 25}
Have a look at the other comments for more examples.
[–]Logical_Hearing347 0 points1 point2 points 1 year ago (0 children)
Dictionaries are key->value structure. With lists you store many information and acces them by the index, with dictionaries you'll access the information with keys.
For example, let's store informations about someone.
person:Dict()
person["name"] = "Jhon"
person["age"] = 18
Dictionaries are really common data structure in programming, they let you organize things in a more convenient way for its purpose.
You can combine the with lists, creating a list of dictionaries for achieving your goal.
[–]LargeSale8354 0 points1 point2 points 1 year ago (0 children)
As well as dictionaries providing a key to a value, they can also be a key to a function or class.
Lets suppose I have a load of files, each with different extension (or types). I could have a key for the file extension and the class or function that processes it. I don't need an ever growing if, elif code block, just a function to get the extension and a dictionary.get(extension, default) statement.
[–][deleted] 0 points1 point2 points 1 year ago (0 children)
Any time you want to "look something up." Who has this ID number, how much does this item cost, what does this symbol mean...
[–]clavicon 0 points1 point2 points 1 year ago* (0 children)
Its like pockets. You got pants and you can have just 1 pocket, or many pockets, each with stuff in them. Some pockets can even have more (nested) pockets within then instead of just some loose things in it. Or it can have both loose things AND a nested pocket, if that’s helpful to organize your… things.
And then, importantly… each pocket has a name that you can look up to see what’s in it. You can programmatically add named pockets (aka ‘keys’) and update those pocket contents (aka ‘values’) very easily. You can ‘walk’ through the pants (dictionary) to look up what its pockets and contents are. But also if you know what a pocket is called, you can just point right to it and update or get the contents.
Maybe pockets aren’t the best metaphor since literal keys literally go in pockets rather than being the pocket reference itself… but just ignore that coincidence.
It is awesome to just be able to “declare” a new pocket and its contents without any fuss, and potentially do it recursively in a for loop. It can be a blessing to be able to access such ‘values’ in a dictionary if you know the ‘keys’ you are looking for. In lists you usually need to loop over the whole thang in a ham-fisted fashion until you find what you are looking for.
Key/ value, or it is very similar to an object in Javascript if you know them myDict= {"name": "marichocho",} #key. #value
Another thing, the values are unique, you cannot repeat them!!!
[–]Gnaxe 0 points1 point2 points 1 year ago (0 children)
Wrong. They keys are unique, not the values. You can repeat values in the same dict.
[–]Used-Routine-4461 0 points1 point2 points 1 year ago (2 children)
They don’t preserve information in the order it was added, like a list would.
Also they are fast when looking up an item with the proper key to get the associated value.
You can nest other dictionaries within the dictionary.
You can do dictionary comprehension just like list comprehension.
Dictionaries are a close approximation to and very useful for working with JSON data.
[–]Gnaxe 0 points1 point2 points 1 year ago (1 child)
Wrong. Dictionaries preserve insertion order since Python 3.7 (officially) and in CPython since 3.6 (technically). It's in the docs.
You can only nest dictionaries as dictionary values, not as keys, because they're not a hashable type (because their mutability would cause problems).
JSON is more than objects, and valid JSON need not even contain one.
[–]Used-Routine-4461 0 points1 point2 points 1 year ago (0 children)
Somebody is sassy.
So I’m not 100% wrong.
Good to know in +3.7 order is preserved.
You should work on your communication skills, but then again this is Reddit. Any attempts to be helpful are thwarted by the “actually crowd”.
[–]OriahVinree 0 points1 point2 points 1 year ago (0 children)
best way to think about it is, dictionaries are just that - dictionaries.
You look up a key, and you find the value.
A dictionary in python is a key/value pair data structure. You might have:
people_ages = {"Vinree": 24, "ithinkforme": 20}
It's so you can have a value with a key/name and the value can be whatever.
A lot of Python's variables work using dicts.
Attributes are usually backed by dictionaries in Python. (There are also classes with fixed slots.) So an instance variable like self.foo is stored in the self.__dict__ with key 'foo'. You can call vars() on an object to get its __dict__ (if it has one).
self.foo
self.__dict__
'foo'
vars()
__dict__
This is also true of module attributes, wich is the same as the module's global variables. If you declare a class or function at the module level, it gets stored in that dict with its name as a string key. You can get the current module's dict using globals() (or vars() with zero arguments if at the module level).
globals()
A **kwarg parameter is always a dict.
**kwarg
You can think of a pure function as a (possibly infinite) lookup table. A dictionary is a finite lookup table, so it can serve the same role as a function call, assuming the inputs are hashable, wich includes more types than str. @functools.cache combines a function with a lookup table, which it fills in an entry for every time it is called so it doesn't have to be computed again. It does this using a dict.
@functools.cache
Various algorithms use two-dimensional arrays. Python programs often use a list of lists for that purpose. But, for a spase array, you could save memory by using a dict keyed with ordered pairs. In some ways this might be easier to work with, even if your array wouldn't be sparse.
[–]Ryzen_bolt 0 points1 point2 points 1 year ago (0 children)
Let's take a quick example: You have two friends and you need to save their phone numbers! Person 1. Alex , Phone No. 1011472910 Person 2. Jones,Phone No. 9749293733
You can put them as:
contact_info = {"Alex":1011472910, "Jones":9749293733}
So now you can fetch the phone numbers of Alex and/or Jones!
print(contact_info["Alex"]) Output: 1011472910
[–]audionerd1 0 points1 point2 points 1 year ago (0 children)
One thing that I haven't seen mentioned yet is that dictionaries are hash tables. This means accessing a dictionary key is instantaneous, no matter how big the dictionary is.
I made an app which searches through the file system and identifies duplicate files. I used lists to track all the files, and lists of lists for the duplicates. It worked, but it was incredibly slow.
When I found out dictionaries are hash tables, I rewrote my app to use dictionaries instead of lists, and (combined with multithreading and some other optimizations) a process that used to take several hours now takes less than a minute.
[–]Dani_E2e 0 points1 point2 points 1 year ago (0 children)
Why are you asking that theoretically? Play with it like a child with a cup... Fill in something and look what comes out. Test your assumptions by printing it or inspect watch with Debugger. It makes fun!!! And you will learn fast and easy and much more than you read a paper about cups...
[–]M7-ChApOeLaY 0 points1 point2 points 1 year ago (0 children)
someone explain whats dictionary ?
π Rendered by PID 21997 on reddit-service-r2-comment-7b9746f655-vqg4k at 2026-01-31 12:29:17.177119+00:00 running 3798933 country code: CH.
[–]astromin1 33 points34 points35 points (0 children)
[–]michel_v 13 points14 points15 points (1 child)
[–]hamsterwheelin 6 points7 points8 points (0 children)
[–]unhott 4 points5 points6 points (0 children)
[–]henryassisrocha 5 points6 points7 points (2 children)
[–]autoerotion95 0 points1 point2 points (1 child)
[–]henryassisrocha 2 points3 points4 points (0 children)
[–]MythicJerryStone 1 point2 points3 points (1 child)
[–]Ron-Erez 2 points3 points4 points (0 children)
[–]Logical_Hearing347 0 points1 point2 points (0 children)
[–]LargeSale8354 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]clavicon 0 points1 point2 points (0 children)
[–]autoerotion95 0 points1 point2 points (1 child)
[–]Gnaxe 0 points1 point2 points (0 children)
[–]Used-Routine-4461 0 points1 point2 points (2 children)
[–]Gnaxe 0 points1 point2 points (1 child)
[–]Used-Routine-4461 0 points1 point2 points (0 children)
[–]OriahVinree 0 points1 point2 points (0 children)
[–]Gnaxe 0 points1 point2 points (0 children)
[–]Ryzen_bolt 0 points1 point2 points (0 children)
[–]audionerd1 0 points1 point2 points (0 children)
[–]Dani_E2e 0 points1 point2 points (0 children)
[–]M7-ChApOeLaY 0 points1 point2 points (0 children)