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.
Method 1: Split dictionary keys and values using inbuilt functions. Here, we will use the inbuilt function of Python that is . keys() function in Python, and . values() function in Python to get the keys and values into separate lists.
Given dictionary with value as lists, slice each list till K. Input : test_dict = {“Gfg” : [1, 6, 3, 5, 7], “Best” : [5, 4, 2, 8, 9], “is” : [4, 6, 8, 4, 2]}, K = 3 Output : {'Gfg': [1, 6, 3], 'Best': [5, 4, 2], 'is': [4, 6, 8]} Explanation : The extracted 3 length dictionary value list.
Python division operation on DictPython division operation can be performed on the elements present in the dictionary using Counter() function along with '//' operator.
The existing answers will work, but they're all essentially re-implementing a function that already exists in the Python standard library: operator.itemgetter()
From the docs:
Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example:
After f = itemgetter(2), the call f(r) returns r[2].
After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]).
In other words, your destructured dict assignment becomes something like:
from operator import itemgetter d = {'key_1': 'value_a', 'key_2': 'value_b'} key_1, key_2 = itemgetter('key_1', 'key_2')(d) # prints "Key 1: value_a, Key 2: value_b" print("Key 1: {}, Key 2: {}".format(key_1, key_2))
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:
# Note: in python 3, items() functions as iteritems() did # in older versions of Python; use it instead ds = sorted(d.iteritems()) name0, name1, name2..., namen = [v[1] for v in ds]
You could also, at least within an object, do something like:
for k, v in dict.iteritems(): setattr(self, k, v)
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:
def func(**kwargs): # Do stuff with labeled args func(**d)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With