Python 从字典中的键打印特定值索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38019716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:13:55  来源:igfitidea点击:

Print specific value index from key in dictionary

pythondictionary

提问by Deuce525

I have a dictionary that has many values per key. How do I print a specific value from that key?

我有一本字典,每个键都有很多值。如何从该键打印特定值?

for example, my key is "CHMI" but it has 14 values associated with it. How do I print only CHMI: 48680value?

例如,我的键是“CHMI”,但它有 14 个与之关联的值。如何仅打印CHMI: 48680值?

CHMI: ['CHMI', '16', '16.09', '15.92', '16.01', '0.02', '0.13', '48680', '17.26', '12.6', '1.96', '12.24', '14.04', '23.15']

回答by Jay Stanley

You have a dictionary with a key:value pair where the value is a list.

您有一个带有键:值对的字典,其中值是一个列表。

To reference values within this list, you do your normal dictionary reference, ie

要引用此列表中的值,请执行正常的字典引用,即

 dict['chmi']

But you need to add a way to manipulate your list. You can use any of the list methods, or just use a list slice, ie

但是您需要添加一种方法来操作您的列表。您可以使用任何列表方法,或者只使用列表切片,即

dict['chmi'][0] 

will return the first element of the list referenced by key chmi. You can use

将返回键 chmi 引用的列表的第一个元素。您可以使用

dict['chmi'][dict['chmi'].index('48680')]

to reference the 48680 element. What I am doing here is calling the

引用 48680 元素。我在这里做的是调用

list.index(ele) 

method, which returns the index of your element, then I am referencing the element by using a slice.

方法,它返回元素的索引,然后我使用切片引用元素。

回答by André Laszlo

Do you want the 8th element of the list, or an element with a specific value? If you already know the value - then you can print it without looking it up in the list so I assume you want to just retrieve one of the elements:

您想要列表的第 8 个元素,还是具有特定值的元素?如果您已经知道该值 - 那么您可以打印它而无需在列表中查找它,所以我假设您只想检索其中一个元素:

print(my_dict['CHMI'][7])

This is equivalent to:

这相当于:

values = my_dict['CHMI']
eight_value = my_dict[7]
print(eigth_value)

If this is not what you need, I'm afraid you'll have to clarify your question a little :)

如果这不是您所需要的,恐怕您必须稍微澄清一下您的问题:)

回答by DeepSpace

Although I don't understand why you would want to do it (if you already know what value you want, why not use it directly?), it can be done with the indexmethod of lists, which returns the index of the provided value in the list

虽然我不明白你为什么要这样做(如果你已经知道你想要什么值,为什么不直接使用它?),它可以用index列表的方法来完成,它返回所提供值的索引列表

d = {'CHMI': ['CHMI', '16', '16.09', '15.92', '16.01', '0.02', '0.13', '48680', '17.26', '12.6', '1.96', '12.24', '14.04', '23.15']}

chmi_values = d['CHMI']

print(chmi_values[chmi_values.index('48680')])
>> '48680'