I am trying to use Python to convert a list
into a dictionary
and I need to help coming up with a simple solution. The list that I would like to convert looks like this:
inv = ['apples', 2, 'oranges', 3, 'limes', 10, 'bananas', 7, 'grapes', 4]
I want to create a dictionary
from this list
, where the items in the even positions (apples, oranges, limes, bananas, grapes) are the keys
, and the items in the odd positions (2, 3, 10, 7, 4) are the values
.
inv_dict = {'apples':2, 'oranges':3, 'limes':10, 'bananas':7, 'grapes':4}
I've tried using something like enumerate
to count the position of the item, and then if it's even, set it as a key
. But then I'm not sure how to match the following number up with it's correct item.
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
Method #1 : Using set() + values() + dictionary comprehension The combination of these methods can together help us achieve the task of getting the unique values. The values function helps us get the values of dictionary, set helps us to get the unique of them, and dictionary comprehension to iterate through the list.
To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
Shortest way:
dict(zip(inv[::2], inv[1::2]))
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