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
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:
Iterating over dictionaries using 'for' loops
(15 answers)
Python - Remove dicts with empty values from list of dictionaries
(1 answer)
Closed 2 years ago.
I have a question regarding a dictionary in python and empty values.
If I had the following dictionary
my_dict={'a':[],
'b':[1],
'c':[],
'd':[]
}
How I could remove empty values [] and appending the keys in an empty list?
my_dict={
'b':[1],
}
and empty_list=['a','c','d'].
With a list I would do as follows (but there are several ways to do the same):
my_dict = list(filter(None, my_dict))
But I have realised I do not know how to do the same in a dictionary.
You can use a dict comprehension to remove empty values:
new_dict = {k: v for k, v in my_dict.items() if v}
Then you can use set difference to get the removed keys:
removed_keys = my_dict.keys() - new_dict.keys()
Just do two explicit iterations for a clean solution -- first calculate the empty_list, then filter down my_dict:
empty_list = [k for k, v in my_dict.items() if len(v) == 0]
my_dict = {k: v for k, v in my_dict.items() if len(v) != 0}
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.
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)
This question already has answers here:
How to filter a dictionary according to an arbitrary condition function?
(7 answers)
Closed 7 years ago.
I have a dict with following structure:
{5:"djdj", 6:"8899", 7:"998kdj"}
The key is int typed and it's not sorted.
Now I want all the elements whose key is >= 6.
Is there easy way to do that?
[v for k,v in mydict.items() if k >= 6]
What do you mean by "elements"?
If you want a dict of key-value pairs with keys ≥6, Python 2.7+ and 3.x support dict comprehensions.
{ k: v for k, v in mydict.items() if k >= 6 }
You can get this in earlier versions of Python
dict( (k, v) for k, v in mydict.items() if k >= 6 ) # Python 2.4+
dict([(k, v) for k, v in mydict.items() if k >= 6]) # Python 2.0+
by using expression generators or list comprehensions.
If you want a list of keys only,
[ k for k in mydict.keys() if k >= 6 ]
filter( lambda k: k >= 6, mydict.keys() )
Similarly, if you want a list of values only,
[ v for k, v in mydict.items() if k >= 6 ]
[ mydict[k] for k in mydict.keys() if k >= 6 ]
map( mydict.get, filter( lambda k: k >= 6, mydict.keys() ) )
It can be done with filter too.
In [9]: data = {5:"djdj", 6:"8899", 7:"998kdj"}
In [10]: dict(filter(lambda x: x[0] > 5, data.items()))
Out[10]: {6: '8899', 7: '998kdj'}
[ mydict[k] for k in filter(lambda x : x > 6, mydict) ]
To get a dictionary right away: (works in both python 2 and 3)
dict( (k,v) for k,v in mydict.items() if k >= 6 )
If you know the largest key and have no missing keys you can also just go through the dictonary directly: [mydict[x] for x in range(6, largest_key+1)]. That would be the most efficient way.
You can use a list comprehension:
mydict = {5:"djdj", 6:"8899", 7:"998kdj"}
print [k for k in mydict if k >= 6] # prints "[6, 7]"
print dict([(k, mydict[k]) for k in mydict if k >= 6]) # prints "{6:"8899", 7:"998kdj"}"
List comprehension seems to be what you seek but with a list of elements as opposed to keys:
a = {5:"djdj", 6:"8899", 7:"998kdj"}
[a[elem] for elem in a if elem >= 6] #should give you "['8866', '998kd']"