简体   繁体   English

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

[英]Print specific value index from key in dictionary

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. 例如,我的键是“ CHMI”,但它具有14个与之关联的值。 How do I print only CHMI: 48680 value? 如何仅打印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']

You have a dictionary with a key:value pair where the value is a list. 您有一本具有key:value对的字典,其中value是一个列表。

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. 将返回键chmi引用的列表的第一个元素。 You can use 您可以使用

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

to reference the 48680 element. 引用48680元素。 What I am doing here is calling the 我在这里所说的是

list.index(ele) 

method, which returns the index of your element, then I am referencing the element by using a slice. 方法,该方法返回元素的索引,然后使用切片来引用该元素。

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 index method 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'

Do you want the 8th element of the list, or an element with a specific value? 您要列表的第8个元素还是具有特定值的元素? 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: 如果您已经知道该值-那么可以打印它而无需在列表中查找它,因此我假设您只想检索以下元素之一:

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 :) 如果这不是您所需要的,恐怕您需要稍微澄清一下您的问题:)

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

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