Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most concise way to create a python dictionary from local variables

In Objective-C, you can use the NSDictionaryOfVariableBindings macro to create a dictionary like this

NSString *foo = @"bar"
NSString *flip = @"rar"
NSDictionary *d = NSDictionaryOfVariableBindings(foo, flip)
// d -> { 'foo' => 'bar', 'flip' => 'rar' }

Is there something similar in python? I often find myself writing code like this

d = {'foo': foo, 'flip': flip}
# or
d = dict(foo=foo, flip=flip)

Is there a shortcut to do something like this?

d = dict(foo, flip) # -> {'foo': 'bar', 'flip': 'rar'}
like image 797
Tony Avatar asked Oct 08 '12 06:10

Tony


People also ask

What is the correct way 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.

What are two ways you can safely look up a key in a dictionary Python?

Some of the ways you can check if a given key already exists in a dictionary in Python are using: has_key() if-in statement/in Operator. get()

How do I print a dictionary neatly in Python?

Use pprint() to Pretty Print a Dictionary in Python Within the pprint module there is a function with the same name pprint() , which is the function used to pretty-print the given string or object. First, declare an array of dictionaries. Afterward, pretty print it using the function pprint. pprint() .

When should you not use a dictionary Python?

Python dictionaries can be used when the data has a unique reference that can be associated with the value. As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn't be modified in the first place.


2 Answers

No, this shortcut in python does not exist.

But perhaps this is what you need:

>>> def test():
...     x = 42
...     y = 43
...     return locals()
>>> test()
{'y': 43, 'x': 42}

Also, python provides globals() and vars() build-in functions for such things. See the doc.

like image 153
defuz Avatar answered Sep 28 '22 05:09

defuz


have you tried vars()

vars([object])
Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, new-style classes use a dictproxy to prevent direct dictionary updates).

so

variables = vars()
dictionary_of_bindings = {x:variables[x] for x in ("foo", "flip")}
like image 29
John La Rooy Avatar answered Sep 28 '22 07:09

John La Rooy