Create a new list
if the val of dict['a'] > 35
:
mydict = {'a':[45,65,78,32], 'b':['red','blue','green','yellow'], 'c':[3.4, 4.5, 6.5, 7.6]}
Python 3.x:
Using itertools.zip_longest(*iterables, fillvalue=None)
:
From the docs:
Make an iterator that aggregates elements from each of the iterables.
If the iterables are of uneven length, missing values are filled-in
with fillvalue. Iteration continues until the longest iterable is
exhausted
print([y for x,y in zip_longest(mydict['a'],mydict['b']) if x > 35])
Python 2.x:
Using itertools.izip_longest(*iterables[, fillvalue])
print([y for x,y in izip_longest(mydict['a'],mydict['b']) if x > 35])
OUTPUT:
['red', 'blue', 'green']
EDIT:
What is the difference between zip()
and zip_longest()
?
Consider the following lists:
x = [1,2,3,4,5]
y = ['a','b','c']
for a,b in zip(x,y):
print(a,b)
OUTPUT:
1 a
2 b
3 c
It clearly skipped the elements 4,5
in the x
since it could not find its correspondings in the y
.
Using zip_longest()
:
x = [1,2,3,4,5]
y = ['a','b','c']
for a,b in zip_longest(x,y):
print(a,b)
OUTPUT:
1 a
2 b
3 c
4 None
5 None
It did not skip the elements in the x
, instead filled the missing ones in the y with a None
.