简体   繁体   English

一键多值的dict

[英]dict with one key and multiple values

I was wondering if there's a way for me to pull a value at a specific index.我想知道是否有办法让我在特定索引处提取值。 Let's say I have a key with multiple values associated with it.假设我有一个具有多个关联值的键。 But in my dictionary I have multiple keys, each key with multiple values.但是在我的字典中,我有多个键,每个键都有多个值。 I want to iterate through the keys and then each respective value associated with that key.我想遍历键,然后遍历与该键关联的每个相应值。 I want to be able to pull the value at the first index and subtract it from the value at the second index.我希望能够提取第一个索引处的值并将其从第二个索引处的值中减去。

d= {108572791: [200356.77, 200358], 108577388: [19168.7, 19169]}

output for key 108572791 would be -1.33
output for key 108577388 would be -.03

I've try reading up on dict and how it works apparently you can't really index it.我已经尝试阅读 dict 以及它是如何工作的,显然你不能真正索引它。 I just wanted to know if there's a way to get around that.我只是想知道是否有办法解决这个问题。

for key, values in total_iteritems():
    for value in values:
       value[0]-value[1]:

Edit:编辑:

Since the question is way different now, I'll address the new subject:由于现在的问题已经不同了,我将讨论新的主题:

d= {108572791: [200356.77, 200358], 108577388: [19168.7, 19169]}
for i in d:
    print("Output for key ",str(i), "would be ",(d[i][1]-d[i][0]))

Output: Output:

Output for key  108572791 would be  1.2300000000104774
Output for key  108577388 would be  0.2999999999992724

Original answer原始答案

Yes.是的。 When you have a dict containing a list as value if you want to obtain a specific value, then you need to address the index in the list.当你有一个包含列表作为valuedict时,如果你想获得一个特定的值,那么你需要处理列表中的索引。 An example is:一个例子是:

a = {'Name':['John','Max','Robert']}

This means that:这意味着:

print(a['Name']) 

Output: Output:

['John','Max','Robert']

Since ['Name'] is a list:由于 ['Name'] 是一个列表:

for i in range(len(a['Name'])):
    print(a['Name'][i]

Output: Output:

John #(Because it's the index 0)
Max #(Index = 1)
Robert #(Index = 2)

If you want a specific value (for instance 'Max' which is index = 1)如果您想要一个特定的值(例如“Max”,即 index = 1)

print(a['Name'][1]

Output: Output:

Max

Depends on how many values in key obvious but this does the trick:取决于明显的键中有多少值,但这可以解决问题:

for x in d:
        print(x)
        print(d[x][0]-d[x][1])

You can use list of tuples if you want to use indexing.如果要使用索引,可以使用元组列表。

d= [(108572791,[200356.77, 200358]), (108577388,[19168.7, 19169)] d= [(108572791,[200356.77, 200358]), (108577388,[19168.7, 19169)]

for tuple in my_list:
   print(tuple[0]) 
   for value in tuple[1]:
       print(value) 

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

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