0

Use dictionary.get() function to output item in imbedded list

In the Python Data structures section on Dictionaries, right before the assignment "fuzzy search" it has a description of how the dictionary.get() function works. The assignment itself involves a dictionary where each key is tied to a two item list. Maybe I'm wrong, but based on how the assignment was on the same page as the get() function lesson, I assumed I was supposed to use the get() function in that assignment. I managed to do it in a very roundabout way, but is there any way to do that in a single line of code? Say I have dict = {"a":[1, 2, 3], "b":[4, 5, 6]}. Is there a way to use dict.get() to return one of the items inside of one of the lists, rather than the full list? I tried dict.get("a"[0], "Not here") but just returned the full [1, 2, 3] list. I also tried dict.get("a", "Not here")[0] and that works when the item is in dict, but if it's not in the dict I'll just get the "N" from "Not here" because it's the first letter. I want it to return 1 on its own, or the full phrase "Not here". Is that possible?

22nd Sep 2021, 11:53 PM
Joel Shircliff
Joel Shircliff - avatar
3 Antworten
+ 2
Hi Joel! Of course, you can do it in a single line of code. For that, you can change "Not here" as a list element. So, get()[0] returns the first element which is the full phrase "Not here" if the key is not found in dict. Here is it what I mentioned above dict = {"a":[1, 2, 3], "b":[4, 5, 6]} print(dict.get("a", ["Not here"])[0]) print(dict.get("c", ["Not here"])[0])
23rd Sep 2021, 4:17 AM
Python Learner
Python Learner - avatar
+ 1
@Python Learner thanks, that makes sense.
23rd Sep 2021, 4:27 AM
Joel Shircliff
Joel Shircliff - avatar