I'm trying to create a dict to not use lots of if statements, but for some reason, I cannot seem to make it work the way I want. I'm trying to pull out only the keys from the dict when the correspond to the inputted day.
Thanks in advance.
edit: expected input/output
Input (Day of Week) | Output (Corresponding key) |
---|---|
'Monday' | 12 |
'Tuesday' | 12 |
'Friday' | 12 |
'Wednesday' | 14 |
'Thursday' | 14 |
'Saturday' | 16 |
'Sunday' | 16 |
day = str(input())
day_price_dict = {12: ['Monday', 'Tuesday', 'Friday'], 14: ['Wednesday', 'Thursday'], 16: ['Saturday', 'Sunday']}
if day in day_price_dict:
print(day_price_dict[day])
Following should do what you want:
# example: day = 'Tuesday'
day = str(input())
day_price_dict = {12: ['Monday', 'Tuesday', 'Friday'], 14: ['Wednesday', 'Thursday'], 16: ['Saturday', 'Sunday']}
# iterate through dict keys (12, 14, 16)
for key in day_price_dict:
# if input is in the value list, print the key
if day in day_price_dict[key]:
# print 12
print(key)
Your conceptualization seems off: What you want is probably a mapping from days to prices rather than vice versa, ie,
>>> day_prices = {'Monday': 12,
'Tuesday': 12,
'Wednesday': 14,
'Thursday': 14,
'Friday': 12,
'Saturday': 16,
'Sunday': 16}
>>> day_prices["Monday"]
12
you can get the keys like this:
keys = day_price_dict.keys()
# if you want a list:
keys = list(day_price_dict.keys())
You can also get the value:
for value in day_price_dict.value():
print(value)
Or both
for key, value in day_price_dict.items():
print(f"key: {key} -- value: {value}")
In Python 3 list() function takes any iterable as a parameter and returns a list. In Python iterable is the object you can iterate over. You can simply use the below lines to get the list of keys.
day_price_dict = {12: ['Monday', 'Tuesday', 'Friday'], 14: ['Wednesday', 'Thursday'], 16: ['Saturday', 'Sunday']}
keys_list = list(day_price_dict.keys())
print(keys_list)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.