Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over dict keys when assigning values to multiple variables

I have a multi-dim dict with primary key being a hash and sub values keyed on single chars. I'm trying to assign a subset of values to multiple vars by iterating over a string containing the chars of the sub-keys I want. Something like:

A,B,C = tree[hash][i] for i in "xyz"

This would equate to:

A = tree[hash]["x"]
B = tree[hash]["y"]
C = tree[hash]["z"]

But trying to do it all in a single line, possibly to imbed in a function where I would pass the list of vars and the corresponding string of sub-keys.

like image 634
MichaelB Avatar asked Jan 27 '23 09:01

MichaelB


1 Answers

You have nearly done that. Just add square brackets around right side expression. It's called list comprehension:

A, B, C = [tree[hash][i] for i in "xyz"]
like image 194
angrysumit Avatar answered Apr 26 '23 23:04

angrysumit