Mapping Python list based on dict value - python

I want to map python list based on values of dict. I know how to do that when I have pandas series, but I do not know how to do it with list:
l = ['apple', 'lemmon', 'banana']
x = {'apple':1, 'lemmon':2, 'banana':3, 'chery':4}
l = l.map(x)
print(l)
Desired output:
l = [1,2,3]

This can be solved with Python list comprehensions.
In your case:
l = [x[key] for key in l]
Note that all elements in l need to exist as keys in x.

Using the dict.get method and the map builtin:
m = list(map(x.get, l))
Note that elements of l that are not keys of x will be mapped to None.

With a comprehension:
>>> [x.get(i) for i in l]
[1, 2, 3]

Related

Comparing list with dictionary to make new list in python

I have one list and one dictionary. I want to compare the list values with the keys of the dictionary. If I have:
mydict = {'Hello':1,'Hi':2,'Hey':3}
and:
mylist = ['Hey','What\'s up','Hello']
I want the output to be:
output = [3, None, 1]
Thanks!
I tried [mydict[i] for i in mylist] and I get an error instead of None. I then tried using nested for loops (I deleted that bit) but I decided that was to inefficient.
Use a list comprehension:
output = [ mydict.get(key) for key in mylist ]
Note that dict.get returns None if the key is not in the dict.
Use dict.get(), which defaults to None if key does not exist:
[mydict.get(k) for k in mylist]
>>> mydict = {'Hello':1,'Hi':2,'Hey':3}
>>> mylist = ['Hey','What\'s up','Hello']
>>> out = [mydict.get(k) for k in mylist]
>>> out
[3, None, 1]

How to sort each individual string in a list of strings?

I want to sort each string in a list of string to be in alphabetical order.
For example,
l1 = ["bba", "yxx", "abc"]
I want to sort it to be
l1 = ["abb", "xxy", "abc"]
I can do it in a for loop but wonder if this is a more pythonic way using python list comprehension. Thanks :D
Using list comprehension and str.join:
>>> l1 = ["bba", "yxx", "abc"]
>>> [''.join(sorted(s)) for s in l1]
['abb', 'xxy', 'abc']
by List compression with sorted method and string join method
>>> l1 = ["bba", "yxx", "abc"]
>>> [''.join(sorted(i)) for i in l1]
['abb', 'xxy', 'abc']
>>>
by lambda
>>> l1
['bba', 'yxx', 'abc']
>>> map(lambda x:"".join(sorted(x)),l1)
['abb', 'xxy', 'abc']
For Python beginner
Iterate every item of list l1 by for loop.
Use sorted() method to sort item and return list.
Use join() method to create string from the list.
Use append() list method to add sored item to new list l2.
print l2
e.g.
>>> l1
['bba', 'yxx', 'abc']
>>> l2 = []
>>> for i in l1:
... a = sorted(i)
... b = "".join(a)
... l2.append(b)
...
>>> l2
['abb', 'xxy', 'abc']
Just use the sorted built-in function.
l1 = ["bba", "yxx", "abc"]
print [''.join(sorted(i)) for i in l1]
Another way of using list comprehensions (if your strings have a fixed length of 3) would be:
print ['{0}{1}{2}'.format(*sorted(i)) for i in l1]

How can I check if a list exist in a dictionary of lists in the same order

Say I have a dictionary of lists,
C = {}
li = []
li.append(x)
C[ind] = li
And I want to check if another list is a member of this dictionary.
for s in C.values():
s.append(w)
Python checks it for any occurrences of the values in s and the dictionary values. But I want to check if any of the lists in the dictionary is identical to the given list.
How can I do it?
Use any for a list of lists:
d = {1 : [1,2,3], 2: [2,1]}
lsts = [[1,2],[2,1]]
print(any(x in d.values() for x in lsts))
True
d = {1:[1,2,3],2:[1,2]}
lsts = [[3,2,1],[2,1]]
print(any(x in d.values() for x in lsts))
False
Or in for a single list:
lst = [1,2]
lst in d.itervalues()
Python will compare each element of both lists so they will have to have the same order to be equal, even if they have the same elements inside the order must also be the same so a simple comparison will do what you want.
in does the trick perfectly, because it does a comparison with each element behind the scenes, so it works even for mutable elements:
lst in d.values()

How to remove a string within a list item in python

On a project I am currently getting returned a list as follows:
[u'40620', u'00700', u'24150', u'11700']
How can I edit the list so it is returned just integer values:
[40620, 00700, 24150, 11700]
Thanks!
Use a list comprehension and int:
>>> lst = [u'40620', u'00700', u'24150', u'11700']
>>> [int(x) for x in lst]
[40620, 700, 24150, 11700]
>>>
Simple one liner:
results = map(int, results)

getting elements in a list according to list of indices in python

I have a list of indices, something like:
b=[0,2]
and a list of elements:
a = ['elem0','elem1','elem2']
I need a list that is composed of the elements in a with the indices in b
(in this example: ['elem0','elem2'])
Use a list comprehension:
[a[i] for i in b]
Or:
from operator import itemgetter
b=[0,2]
a = ['elem0','elem1','elem2']
print itemgetter(*b)(a)
>>> ('elem0','elem2')
Use a list comprehension to map the indexes to the list:
b=[0,2]
a = ['elem0','elem1','elem2']
sublist = [a[i] for i in b]
>ipython
In [1]: b=[0,2]
In [2]: a = ['elem0','elem1','elem2']
In [3]: [a[i] for i in b]
Out[3]: ['elem0', 'elem2']
Look up "list comprehensions" in the python manual if you don't know them.

Categories

Resources