Home > Back-end >  How do I access list values in a dictionary based on key matches in Python?
How do I access list values in a dictionary based on key matches in Python?

Time:12-28

{'A': [5.0, 6.20], 'B': [1.92, 3.35], 'C': [3.21, 7.0], 'D': [2.18, 9.90]}

I will then manipulate the numbers according to the key matches.

So for example, A, I'd take those numbers and plug-into an equation accordingly.

x/100 * y/100 = 5.0/100 * 6.20/100

Note that this is part of a function that returns values.

CodePudding user response:

You can use a dict comprehension to do this for each key.

{k:(x/100) * (y/100) for k,(x,y) in d.items()}
{'A': 0.0031000000000000003,
 'B': 0.0006432,
 'C': 0.002247,
 'D': 0.0021582000000000003}

Accessing a single key's value in a dictionary is as simple as just d['A'] or d.get('A')

Read more about dict comprehensions here.

EDIT: Thanks for the cleaner code suggestion @Olvin Roght

CodePudding user response:

After accessing the dictionary values with their key, in this example 'A' then access the list values with their index. Index [0] of the list holds 'val1' for example. Which you can then assign to a variable and do your math.

dict

Code


dic = {'A':['val1', 'val2']}

x = dic['A'][0]
y = dic['A'][1]

print(x, y)

Result


val1 val2
  • Related