Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List to Dictionary: Even items as keys, odd items as values [duplicate]

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.

like image 534
CurtLH Avatar asked Jul 05 '16 02:07

CurtLH


People also ask

Can key in dictionary have duplicate values?

First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

How do I get a list of unique values from a dictionary?

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.

How do I turn a list into a dictionary?

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.


1 Answers

Shortest way:

dict(zip(inv[::2], inv[1::2]))
like image 116
min2bro Avatar answered Oct 04 '22 16:10

min2bro