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'}
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.
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()
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() .
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.
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.
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")}
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