Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more pythonic way to build this dictionary?

Tags:

python

What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: values is a list that is not related to any dictionary.

for value in values:
    new_dict[key_from_value(value)] = value
like image 617
Hank Gay Avatar asked Apr 15 '09 22:04

Hank Gay


People also ask

How many ways are there to create a dictionary in Python?

A dictionary in Python is made up of key-value pairs. In the two sections that follow you will see two ways of creating a dictionary. The first way is by using a set of curly braces, {} , and the second way is by using the built-in dict() function.

Which method is used to create a dictionary in Python?

Python dict() Method The dict() method creates a dictionary object from the specified keys and values, or iterables of keys and values or mapping objects.


2 Answers

At least it's shorter:

dict((key_from_value(value), value) for value in values)
like image 80
Hank Gay Avatar answered Oct 14 '22 00:10

Hank Gay


>>> l = [ 1, 2, 3, 4 ]
>>> dict( ( v, v**2 ) for v in l )
{1: 1, 2: 4, 3: 9, 4: 16}

In Python 3.0 you can use a "dict comprehension" which is basically a shorthand for the above:

{ v : v**2 for v in l }
like image 45
kurosch Avatar answered Oct 14 '22 00:10

kurosch