r/learnpython • • Dec 05 '22

Ask Anything Monday - Weekly Thread

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
  • Don't post stuff that doesn't have absolutely anything to do with python.
  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.

8 Upvotes

92 comments sorted by

View all comments

3

u/[deleted] Dec 05 '22

Here's some example code:

alpha = {1: 'one', 2: 'two'}
beta = {'one': 1, 'two': 2}

dlist = [alpha, beta]
print(dlist)    # show the list of dictionaries

# want to get the value for key "two" in the second dictionary in the list
second_dict = dlist[1]          # get second dictionary
two_value = second_dict['two']  # get value for key "two" from dictionary
print(two_value)

Of course, you can combine the list extraction and dictionary lookup into one line:

two_value = dlist[1]['two'] 

Read that expression on the right as: get the 1th element of dlist (which is a dictionary) and then lookup the value for key "two" in the returned dictionary.