Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using locals() inside dictionary comprehension

The following code doesn't work, I assume because the locals() variable inside the comprehension will refer to the nested block where comprehension is evaluated:

def f():
    a = 1
    b = 2
    list_ = ['a', 'b']
    dict_ = {x : locals()[x] for x in list_}

I could use globals() instead, and it seems to work, but that may come with some additional problems (e.g., if there was a variable from a surrounding scope that happens to have the same name).

Is there anything that would make the dictionary using the variables precisely in the scope of function f?

Note: I am doing this because I have many variables that I'd like to put in a dictionary later, but don't want to complicate the code by writing dict_['a'] instead of a in the meantime.

like image 729
max Avatar asked Nov 01 '10 00:11

max


People also ask

Can you do dictionary comprehension in Python?

Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions.

Why do we use dictionary comprehension in Python?

Dictionaries in Python allow us to store a series of mappings between two sets of values, namely, the keys and the values. All items in the dictionary are enclosed within a pair of curly braces {} . Each item in a dictionary is a mapping between a key and a value - called a key-value pair.

What is dictionary and list comprehension in Python?

List comprehensions and dictionary comprehensions are a powerful substitute to for-loops and also lambda functions. Not only do list and dictionary comprehensions make code more concise and easier to read, they are also faster than traditional for-loops.


2 Answers

You could perhaps do this:

def f(): 
    a = 1 
    b = 2 
    list_ = ['a', 'b'] 
    locals_ = locals()
    dict_ = dict((x, locals_[x]) for x in list_)

However, I would strongly discourage the use of locals() for this purpose.

like image 82
Greg Hewgill Avatar answered Oct 23 '22 04:10

Greg Hewgill


I believe that you're right: the locals() inside the dict comprehension will refer to the comprehension's namespace.

One possible solution (if it hasn't already occurred to you):

f_locals = locals()
dict_ = {x : f_locals[x] for x in list_}
like image 30
David Wolever Avatar answered Oct 23 '22 04:10

David Wolever