I am studying Python and currently going through some more learning with dictionaries.
I was wondering;
If I have a dictionary like: d = {'key_1': 'value_a', 'key_2': 'value_b'} and I want separate/divide this dictionary into variables where each variable is a key from the dictionary and each variables value is the value of that key in the dictionary.
What would be the best pythonic way to achieve this?
d = {'key_1': 'value_a', 'key_2': 'value_b'}
#perform the command and get
key_1 = 'value_a'
key_2 = 'value_b'
I tried: key_1, key_2 = d but it did not work.
Basically I am seeking expert’s wisdom to find out if there is a better way to reduce 2 lines of code into one.
Note: This is not a dynamic variable creation.
Problem is that dicts are unordered, so you can’t use simple unpacking of
d.values(). You could of course first sort the dict by key, then unpack the values:You could also, at least within an object, do something like:
Additionally, as I mentioned in the comment above, if you can get all your logic that needs your unpacked dictionary as variables in to a function, you could do: