简体   繁体   English

如何仅从字典中提取键

[英]How do I pull out only the keys from the dictionary

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.我正在尝试创建一个不使用大量 if 语句的 dict,但由于某种原因,我似乎无法让它按我想要的方式工作。 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) Output(对应键)
'Monday' '周一' 12 12
'Tuesday' '周二' 12 12
'Friday' '星期五' 12 12
'Wednesday' '周三' 14 14
'Thursday' '周四' 14 14
'Saturday' '周六' 16 16
'Sunday' '星期日' 16 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.在 Python 3 list() function 将任何可迭代对象作为参数并返回一个列表。 In Python iterable is the object you can iterate over.在 Python 中可迭代的是 object 您可以迭代。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM