This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
my problem is that I need a some variables and parameters which are in string form in dictionary and the values are in both shape (string and integer)
For example :
d={'a6':'36','a21':52}
Now I want these to use them in next steps in some math formulas:
a6=36.0
a21=52.0
Is there anyway to change those keys which are in string forms to these variables?
You could just do:
for key,val in d.items():
vars()[key] = int(val)
>> a6
36
You can do it in a single line with:
>>> d = {'a': 1, 'b': 2}
>>> locals().update(d)
>>> a
1
or:
>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
exec(key + '=val')
#list(map(exec, ("{0}={1}".format(x[0],x[1]) for x in d.items())))
Try:
for k, v in d.items():
exec("%s = %s" % (k, v))
Please note that using exec (or eval) can create a substantial security risk if you don't have complete control over the inputs.
Related
This question already has answers here:
filter items in a python dictionary where keys contain a specific string
(6 answers)
Closed 8 months ago.
d = {'a1':1, 'a2':2,'a3':3,'a4':1,'a5':1,'b':2, 'c':3}
for k, v in d.copy().items():
if 'a' in k:
del d[k]
print(d)
I want to delete elements if the key or value meets a certain requirement, as above, in which the keys containing 'a' will be deleted.
In particular, can I somehow not use the copy() function to do the same thing?
EDIT: Based on suggestion, I adopted this way:
for k in list(d):
if 'a' in k:
del d[k]
Create a new dictionary without the key you want to filter
d = {'a1':1, 'a2':2,'a3':3,'a4':1,'a5':1,'b':2, 'c':3}
filtered_d = {k: v for k,v in d.items() if 'a' not in k}
This question already has answers here:
Create a dictionary with comprehension
(17 answers)
Closed 2 years ago.
Been informed this has been answered - apoligies
Thank you!
Since you wanted a function to perform this:
def newprice(d):
return {"all" + key: value * 5 for key, value in d.items()}
# To be used as :
dict1 = {'apple':5, 'banana':4}
print(newprice(dict1))
In dictionary comprehension you can do whatever you want to keys and values:
def newprice(d):
return {f'all{k}': v * 5 for k, v in d.items()}
Here you go -
dict1 = {'apple':5, 'banana':4}
dict2 = {('all'+ k): 5*dict1[k] for k in dict1 }
print(dict2)
This question already has an answer here:
Zip list of tuples with flat list
(1 answer)
Closed 6 years ago.
I am trying to enumerate through a dictionary like this but it does not work. What's the simplest way to iterate through a dictionary in python while enumerating each entry?
for i, k, v in enumerate(my_dict.iteritems()):
print i, k, v
You just need to add parenthesis around (k, v) tuple:
>>> d = {1: 'foo', 2: 'bar'}
>>> for i, (k, v) in enumerate(d.iteritems()):
... print i, k, v
...
0 1 foo
1 2 bar
This question already has answers here:
Order of keys in dictionaries in old versions of Python
(6 answers)
Closed 8 years ago.
I've run into a problem with looping through a dictionary. The following code:
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
for k,v in d.iteritems():
print k,v
Results in:
a 1
c 3
b 2
But the desired result is:
a 1
b 2
c 3
Does anyone know how to fix the loop somehow to preserve the order that the elements were assigned in? Thank you!
In Python, normal dictionaries were designed to be unordered. Meaning, they should not be used here.
Instead, you should use a collections.OrderedDict:
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d['a'] = 1
>>> d['b'] = 2
>>> d['c'] = 3
>>> for k,v in d.iteritems():
... print k,v
...
a 1
b 2
c 3
>>>
Unlike a normal dictionary, an OrderedDict is guaranteed to preserve the order in which the elements were assigned.
A dictionary does not preserve order, so you need to sort the keys:
for k,v in sorted(d.iteritems,key=lambda x: x[0]):
print k,v
Alternatively, use a collections.OrderedDict object which internally maintains a list of keys in insertion order:
import collections
d = collections.OrderedDict()
...
for k,v in d.iteritems():
print k,v
This question already has answers here:
Two way/reverse map [duplicate]
(15 answers)
Closed 10 years ago.
dictionary is usually good for find value by key,but find key by value is pretty slow
for k,v in dictionary.items():
if v = myValue:
return k
is there already a data structure that make both key->value and ke
You could try bidict:
>>> husbands2wives = bidict({'john': 'jackie'})
>>> husbands2wives['john'] # the forward mapping is just like with dict
'jackie'
>>> husbands2wives[:'jackie'] # use slice for the inverse mapping
'john'
Just create an inverted mapping:
from collections import defaultdict
inverted = defaultdict(list)
for k, v in dictionary.iteritems():
inverted[v].append(k)
Note that the above code handles duplicate values; inverted[v] returns a list of keys that hold that value.
If your values are also unique, a simple dict can be used instead of defaultdict:
inverted = { v: k for k, v in dictionary.iteritems() }
or, in python 3, where items() is a dictionary view:
inverted = { v: k for k, v in dictionary.items() }
Python 3:
revdict = {v:k for k,v in dictionary.items()}
(Python 2 use .iteritems() instead)