Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional select dictionary value in Python

I have a dictionary:

varpr = {'values': ['pr', 'tas'],
 'names': ['Precipitation [mm]', 'Temperature [C deg]']}

How can I select names field if values == pr? I expect something like x = 'Precipitation [mm]'

T try:

var = 'pr'
[v for k,v in varpr.items() if k == 'values' and v == 'pr']

but got null.

like image 1000
Peter.k Avatar asked Feb 28 '26 23:02

Peter.k


2 Answers

Try below to get required output:

[k for k,v in zip(varpr['names'], varpr['values']) if v == 'pr']

#  ['Precipitation [mm]']
like image 164
Andersson Avatar answered Mar 02 '26 13:03

Andersson


Possibly more appropriate is to define a new, restructured dictionary. Then just query the dictionary:

d = dict(zip(varpr['values'], varpr['names']))

print(d)
# {'pr': 'Precipitation [mm]', 'tas': 'Temperature [C deg]'}

print(d['pr'])
# Precipitation [mm]
like image 24
jpp Avatar answered Mar 02 '26 13:03

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!