How to extract only certain values from a dictionary (python) - python

Let's say that I have a list l=[1, 2, 3, 4] and a dictionary d={2:a, 4:b}.
I'd like to extract the values of d only in the key is also in my list and put the result in a new list.
This is what I've tried so far:
new_l=[]
for i in l:
for key in d.keys():
if key in l:
new_l.append(d[key])
print (new_l)
Thank you in advance for your help.

This will compare each value in the dictionary and if it's match in the list.
Simplistic answer..
>>> l
[1, 2, 3, 4]
>>> d
{2: 'a', 4: 'b'}
>>> [value for (key,value) in d.items() if key in l]
['a', 'b']

You don't need to cycle through each key in that second for loop. With Python, you can just use a list comprehension:
L = [1, 2, 3, 4]
d = {2: 'a', 4: 'b'}
res = [d[i] for i in L if i in d] # ['a', 'b']
An alternative functional solution is possible if you know your dictionary values are non-Falsy (e.g. not 0, None). filter is a lazy iterator, so you'll need to exhaust via list in a subsequent step:
res = filter(None, map(d.get, L))
print(list(res)) # ['a', 'b']

You can skip iterating l
Ex:
l=[1, 2, 3, 4]
d={2:"a", 4:"b"}
new_l=[]
for key in d.keys():
if key in l:
new_l.append(d[key])
print (new_l)

Iterate the dictionary with key and match the key present in list.
L=[1, 2, 3, 4]
d={2:"a", 4:"b"}
new_l=[]
for k in d.keys():
if k in L:
new_l.append(d[k])
print (new_l)

Related

List comprehension with early conditional check

For the given list l
l = [{'k': [1, 2]}, {'k': [2, 8]}, {'k': [6, 32]}, {}, {'s': 0}]
where I would like to have a single list of all values
r = [1, 2, 2, 8, 6, 32]
and the code
r = []
for item in l:
if 'k' in item:
for i in item['k']:
r += [i]
is there an elegant list comprehension solution for this kind of list?
Obviously,
[i for i in item['k'] if 'k' in item for item in l]
fails, because item['k'] is accessed before the condition is checked. Any ideas?
Use get to provide an empty list to iterate over if k doesn't exist.
r = [i for d in l for i in d.get('k', [])]
Or, check for k before you try to access its value.
r = [i for d in l if 'k' in d for i in d['k']]
You almost have the right solution with your list comprehension. It is just that the order of statements inside list comprehension is wrong. Please try the following.
l = [{'k': [1, 2]}, {'k': [2, 8]}, {'k': [6, 32]}, {}, {'s': 0}]
answer = [i for item in l if 'k' in item for i in item['k'] ]
print(answer)
Is this what you wanted?

Python: how to search within a homogenous values dictionary

I have this dictionary:
dict = {'a': [1, 'Hello', 3], 'b': {1, 2, 90}, 'c': (1, 2, 'tuple'), 'd': 3}
I tried to print each key contains the value 3. The output has to be a and d
I tired something like this:
[key for key, vals in dict.items() if 3 in vals]
but an error: int is not iterable
I also tried to use for :
>>> for i in dict.values():
... if 3 in dict.values():
... print(i)
I also tried this but nothing works
>>> for i in dict.keys():
... if 3 in dict[i]:
... print(i)
PART 2: Let us say I am able to print the key if the value contains 3, then how can I get the index if the value is list or tuple?
[key for key, vals in dict.items() if 3==vals or 3 in vals]
The error you get is because not all your values are of the same type.
Your evaluation needs to be if key equals to 3 then return true, or if the value is a container, check if 3 is part of it.
To get an index of a value in a list OR a tuple, you can use
>>> l = [1, 2, 'just', 3, 'p']
>>> l.index(3)
3
>>> t = (1, 2, 'word', 3)
>>> t.index(3)
3
>>>
for k, v in dict.items():
try:
if 3 in v:
print(k)
except TypeError:
if v == 3:
print(k)
Another way is to test if the value of the key is not scalar, before trying to use in:
def in_key(value, vals):
if isinstance(vals, (list, tuple, set)):
return value in vals
else:
return value == vals
lst = [key for key, vals in dict.items() if in_vals(3, vals)]
Your code is almost right, just check the item equal or contained in a set of vals:
dict = {'a': [1, 'Hello', 3], 'b': {1, 2, 90}, 'c': (1, 2, 'tuple'), 'd': 3}
print [key for key, vals in dict.items() if 3 == vals or 3 in vals]
['a', 'd']
Here you have a live example

iterate over only two keys of python dictionary

What is the pythonic way to iterate over a dictionary with a setup like this:
dict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6}
if I only wanted to iterate a for loop over all the values in a and b and skip c. There's obviously a million ways to solve this but I'd prefer to avoid something like:
for each in dict['a']:
# do something
pass
for each in dict['b']:
# do something
pass
of something destructive like:
del dict['c']
for k,v in dict.iteritems():
pass
The more generic way is using filter-like approaches by putting an if in the end of a generator expression.
If you want to iterate over every iterable value, filter with hasattr:
for key in (k for k in dict if hasattr(dict[k], '__iter__')):
for item in dict[key]:
print(item)
If you want to exclude some keys, use a "not in" filter:
invalid = set(['c', 'd'])
for key in (k for k in dict if key not in invalid):
....
If you want to select only specific keys, use a "in" filter:
valid = set(['a', 'b'])
for key in (k for k in dict if key in valid):
....
Similar to SSDMS's solution you can also just do:
mydict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6}
for each in mydict['a']+mydict['b']:
....
You can use chain from the itertools module to do this:
In [29]: from itertools import chain
In [30]: mydict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6}
In [31]: for item in chain(mydict['a'], mydict['b']):
...: print(item)
...:
1
2
3
3
4
5
To iterate over only the values the keys' value in the dictionary that are instance of list simply use chain.from_iterable.
wanted_key = ['a', 'b']
for item in chain.from_iterable(mydict[key] for key in wanted_key if isinstance(mydict[key], list)):
# do something with the item

An efficient way of replacing list of keys with dict values?

Say I have a list of keys belonging in a dictionary:
dict = {"a":[1,2], "b":[3,4], "c":[5,6]}
keys = ["a","b","c"]
What's the most efficient way to replace all the keys in the list with the values in the dictionary?
ie,
keys = ["a","b","c"]
becomes
keys = [[1,2],[3,4],[5,6]]
map makes it easy:
map(d.get, keys)
(Or, in Python 3.x, list(map(d.get, keys)))
Use a list comprehension like so:
>>> # Please don't name a dictionary dict -- it overrides the built-in
>>> dct = {"a":[1,2], "b":[3,4], "c":[5,6]}
>>> keys = ["a","b","c"]
>>> id(keys)
28590032
>>> keys[:] = [dct[k] for k in keys]
>>> keys
[[1, 2], [3, 4], [5, 6]]
>>> id(keys)
28590032
>>>
[:] is only needed if you want the list object to remain the same. Otherwise, you can remove it:
>>> dct = {"a":[1,2], "b":[3,4], "c":[5,6]}
>>> keys = ["a","b","c"]
>>> id(keys)
28561280
>>> keys = [dct[k] for k in keys]
>>> keys
[[1, 2], [3, 4], [5, 6]]
>>> id(keys)
28590032
>>>
If you want a list of ALL the values from a dict, use
>>> d={1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> d.values()
['a', 'b', 'c', 'd']
which returns a list of all contained values.
If you want a subset of the keys, you could use:
>>> d={1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> l=[1, 3]
>>> [d[x] for x in l]
['a', 'c']
Please let me know which you were going for...

python2: merge a list of csv elements

I have a dict like this:
{1: ['1,2,3', '4,5,6', '7,8']}
the dict can be variable in the number of list items but always 1 dict item. How do I merge it to
{1: ['1,2,3,4,5,6,7,8']}
?
Thanks
>>> d
{1: ['1,2,3', '4,5,6', '7,8'], 2: ['9,10', '11']}
>>> for k,v in d.iteritems():
... d[k] = [",".join(v)]
...
>>> d
{1: ['1,2,3,4,5,6,7,8'], 2: ['9,10,11']}
in your case, you just need concat a string.
But if you want to merge the collection, try this:
a = [1, 2, 3]
b = [3, 4, 5]
a.extend(b)
print a
[1, 2, 3, 3, 4, 5]

Categories

Resources