I know this is possible with list comprehension but I can't seem to figure it out. Currently I have a list of dictionaries like so:
[ {'field1': 'a', 'field2': 'b'},
{'field1': 'c', 'field2': 'd'},
{'field1': 'e', 'field2': 'f'} ]
I'm trying to turn this into:
list = [
['b', 'a'],
['d', 'c'],
['f', 'e'],
]
You can try:
[[x['field2'], x['field1']] for x in l]
where l is your input list. The result for your data would be:
[['b', 'a'], ['d', 'c'], ['f', 'e']]
This way you ensure that the value for field2 comes before the value for field1
Just return the dict.values() lists in Python 2, or convert the dictionary view to a list in Python 3:
[d.values() for d in list_of_dicts] # Python 2
[list(d.values()) for d in list_of_dicts] # Python 3
Note that the values are not going to be in any specific order, because dictionaries are not ordered. If you expected them to be in a given order you'd have to add a sorting step.
I'm not sure what ordering you want, but for no order you could do:
list_ = [list(_.values()) for _ in dict_list]
You can use list comprehension
Python 3
>>>listdict = [ {'field1': 'a', 'field2': 'b'},
... {'field1': 'c', 'field2': 'd'},
... {'field1': 'e', 'field2': 'f'} ]
>>>[[a for a in dict.values()] for dict in listdict]
[['b', 'a'], ['d', 'c'], ['f', 'e']]
Python 2
>>>[dict.values() for dict in listdict]
[['b', 'a'], ['d', 'c'], ['f', 'e']]
Related
I want to replace the elements in a list of lists based on a dictionary mapping table, and tried below:
lists_before = [['A', 'B', 'C'], ['A', 'D'], ['D', 'E']]
mapped_dictionary = {'A': 'G', 'B': 'G', 'C':'F'}
Below is the code I use:
lists_after = []
for element in lists_before:
new_element = []
for letter in element :
if letter in list(mapped_dictionary.values()):
letter = repl_dic.get(letter)
new_element.append(letter)
lists_after.append(new_element)
The output expected for lists_after is:
[['G', 'G', 'F'],['G','D'],['D','E']]
However, the output I got is still the same as lists_before.
I cannot figure out what went wrong. Could someone help me?
You can do it like this:
Input:
l = [['A', 'B', 'C'], ['A', 'D'], ['D', 'E']]
m = {'A': 'G', 'B': 'G', 'C': 'F'}
Code:
l_new = list()
for lst in l:
lst_new = list()
for ele in lst:
lst_new.append(m.get(ele, ele))
l_new.append(lst_new)
Output:
[['G', 'G', 'F'], ['G', 'D'], ['D', 'E']]
Or use a 1-liner:
[[m.get(ele, ele) for ele in lst] for lst in l]
[['G', 'G', 'F'], ['G', 'D'], ['D', 'E']]
I want to change a list to a dictionary and also want to make the first element of the list as key of dictionary and other elements will be the result of this key in dictionary. Thanks in advance.
This what I have :
lst = ['a', 'b', 'c', 'd']
print (list)
['a', 'b', 'c', 'd']
and this is what I desir:
dic = {'a':['b', 'c', 'd']}
print(dic)
{'a': ['b', 'c', 'd']}
or
print (dic['a'])
['b', 'c', 'd']
you can try:
lst = ['a', 'b', 'c', 'd']
dct = {lst[0]:lst[1:]}
It will give you the desired result
I thought of a function in case you need to do do this for several lists.
def todict (lst):
first, *rest = lst
return {first: rest}
In[1]: todict(lst)
Out[1]: {'a': ['b', 'c', 'd']}
I have a 2D list such as this:
lst = [['c', 'd', 'b'], ['d', 'c', 'a'], ['b', 'a', 'c']]
I would first like to sort each list within the list alphabetically like this:
lst = [['b', 'c', 'd'], ['a', 'c', 'd'], ['a', 'b', 'c']]
And finally, I would like to sort the whole list alphabetically which takes into account each element in a sublist:
lst = [['a', 'b', 'c'], ['a', 'c', 'd'], ['b', 'c', 'd']]
What would be the fastest way to achieve this? Thank you.
The fastest way in general should be just as you described it:
for sublist in lst:
sublist.sort()
lst.sort()
Alternatively, if you want to do it out of place:
new_lst = [sorted(sublist) for sublist in lst]
new_lst.sort()
I have the following list:
initial_list = [['B', 'D', 'A', 'C', 'E']]
On each element of the list I apply a function and put the results in a dictionary:
for state in initial_list:
next_dict[state] = move([state], alphabet)
This gives the following result:
next_dict = {'D': ['E'], 'B': ['D'], 'A': ['C'], 'C': ['C'], 'E': ['D']}
What I would like to do is separate the keys from initial_list based on their
values in the next_dict dictionary, basically group the elements of the first list to elements with the same value in the next_dict:
new_list = [['A', 'C'], ['B', 'E'], ['D']]
'A' and 'C' will stay in the same group because they have the same value 'C', 'B' and 'D' will also share the same group because their value is 'D' and then 'D' will be in it's own group.
How can I achieve this result?
You need groupby, after having sorted your list by next_dict values :
It generates a break or new group every time the value of the key
function changes (which is why it is usually necessary to have sorted
the data using the same key function).
from itertools import groupby
initial_list = ['B', 'D', 'A', 'C', 'E']
def move(letter):
return {'A': 'C', 'C': 'C', 'D': 'E', 'E': 'D', 'B': 'D'}.get(letter)
sorted_list = sorted(initial_list, key=move)
print [list(v) for k,v in groupby(sorted_list, key=move)]
#=> [['A', 'C'], ['B', 'E'], ['D']]
Simplest way to achieve this will be to use itertools.groupby with key as dict.get as:
>>> from itertools import groupby
>>> next_dict = {'D': ['E'], 'B': ['D'], 'A': ['C'], 'C': ['C'], 'E': ['D']}
>>> initial_list = ['B', 'D', 'A', 'C', 'E']
>>> [list(i) for _, i in groupby(sorted(initial_list, key=next_dict.get), next_dict.get)]
[['A', 'C'], ['B', 'E'], ['D']]
I'm not exactly sure that's what you want but you can group the values based on their values in the next_dict:
>>> next_dict = {'D': 'E', 'B': 'D', 'A': 'C', 'C': 'C', 'E': 'D'}
>>> # external library but one can also use a defaultdict.
>>> from iteration_utilities import groupedby
>>> groupings = groupedby(['B', 'D', 'A', 'C', 'E'], key=next_dict.__getitem__)
>>> groupings
{'C': ['A', 'C'], 'D': ['B', 'E'], 'E': ['D']}
and then convert that to a list of their values:
>>> list(groupings.values())
[['A', 'C'], ['D'], ['B', 'E']]
Combine everything into a one-liner (not really recommended but a lot of people prefer that):
>>> list(groupedby(['B', 'D', 'A', 'C', 'E'], key=next_dict.__getitem__).values())
[['A', 'C'], ['D'], ['B', 'E']]
Try this:
next_next_dict = {}
for key in next_dict:
if next_dict[key][0] in next_next_dict:
next_next_dict[next_dict[key][0]] += key
else:
next_next_dict[next_dict[key][0]] = [key]
new_list = next_next_dict.values()
Or this:
new_list = []
for value in next_dict.values():
new_value = [key for key in next_dict.keys() if next_dict[key] == value]
if new_value not in new_list:
new_list.append(new_value)
We can sort your list with your dictionary mapping, and then use itertools.groupby to form the groups. The only amendment I made here is making your initial list an actual flat list.
>>> from itertools import groupby
>>> initial_list = ['B', 'D', 'A', 'C', 'E']
>>> next_dict = {'D': ['E'], 'B': ['D'], 'A': ['C'], 'C': ['C'], 'E': ['D']}
>>> s_key = lambda x: next_dict[x]
>>> [list(v) for k, v in groupby(sorted(initial_list, key=s_key), key=s_key)]
[['A', 'C'], ['B', 'E'], ['D']]
I have a list as follows:
l = [['A', 'C', 'D'], ['B', 'E'], ['A', 'C', 'D'], ['A', 'C', 'D'], ['B', 'E'], ['F']]
The result should be:
[['A', 'C', 'D'], ['B', 'E'], ['F']]
The order of elements is also not important.
I tried as:
print list(set(l))
Does numpy has better way
Lists are not a "hashable" type and cannot be members of a set.
Frozen sets can, so we first convert to those (also making the sublists order-insentive), and later convert back to lists.
print map(list, set(map(frozenset, l)))
or if you prefer comprehensions,
print [list(x) for x in {frozenset(x) for x in l}]
I doubt numpy offers any "better" (for some definition of better) way.
This way is IMO the clearest and most pythonic.
The reason lists cannot be part of sets is that they are mutable, so the hash now is different from the hash after they are changed; being in a hash-based set would make for confusing behavior.
#!/usr/bin/python
l1 = [['A', 'C', 'D'], ['B', 'E'], ['A', 'C', 'D'], ['A', 'C', 'D'], ['B', 'E'], ['F']]
l2=[]
for l in l1:
if l not in l2:
l2.append(l)
print l2
OUTPUT
[['A', 'C', 'D'], ['B', 'E'], ['F']]
The easiest and straightforward approach where you don't need to convert a non hashable type to hashable and vice versa (which has a performance impact), is to use itertools.groupby
Off-course, the order won;t be maintained but in any case OP categorically specified that it is not a strict requirement
>>> l = [['A', 'C', 'D'], ['B', 'E'], ['A', 'C', 'D'], ['A', 'C', 'D'], ['B', 'E'], ['F']]
>>> from itertools import groupby
>>> [k for k, g in groupby(sorted(l))]
[['A', 'C', 'D'], ['B', 'E'], ['F']]