How to convert list of dictionaries to list of tuples? - python

I have a list of dictionaries in python like:
lst = [{'f_id': '1', 'm_id':'22', 'fm_id':'23'},{'f_id': '2', 'm_id':'32', 'fm_id':33}]
I'm trying to update the values in dictionary like
lst = [{'f_id': '3', 'm_id':'22', 'fm_id':'N'},{'f_id': '4', 'm_id':'32', 'fm_id':N}]
and get only values from dictionary and put them in list of tuples like:
new_lst = [('3', '22', 'N'),('4', '32', 'N')]
I've tried:
list_of_dict = []
for each in lst:
for key, values in each.items():
temp = values
list_of_dict.append(temp)
print(list_of_dict)
but I'm getting a different output. I'm tried different approaches but not getting the expected output.

Have you tried this?
lst = [{'f_id': '1', 'm_id':'22', 'fm_id':'23'},{'f_id': '2', 'm_id':'32', 'fm_id': '33'}]
new_lst = [tuple(d.values()) for d in lst]

Here is a one liner solution:
j=[tuple([str(x) for x in d.values()]) for d in lst ]
Output:
[('1', '22', '23'), ('2', '32', '33')]

Related

How to delete duplicates in dictionary with list values

I need to delete the elements that are duplicated in a dictionary like this:
{
1: ['1', '2', '3'],
2: ['4', '3', '6', '7'],
3: ['8', '1', '9']
}
as to make the final result like this
{
1: ['1', '2', '3'],
2: ['4', '6', '7'],
3: ['8', '9']
}
Please help me how to do that, I have no idea
Assuming d the input, you can use a set to keep track of the seen values. Here using a dictionary comprehension and "cheating" a bit to add the values:
seen = set()
out = {k: [x for x in v
if x not in seen and not seen.add(x)]
for k,v in d.items()}
Output:
{1: ['1', '2', '3'],
2: ['4', '6', '7'],
3: ['8', '9']}
Same with a classical loop:
out = {}
seen = set()
for k,v in d.items():
l = []
for x in v:
if x not in seen:
seen.add(x)
l.append(x)
out[k] = l
Rehashing the same old seen-set solution is boring :-P. Let's have some fun with Counters:
from collections import Counter
d = {
1: ['1', '2', '3'],
2: ['4', '3', '6', '7'],
3: ['8', '1', '9']
}
seen = Counter()
for a in d.values():
uniq = Counter(dict.fromkeys(a, 1))
a[:] = uniq - seen
seen |= uniq
print(d)
Each list is first deduplicated on its own by using a dict. Then turned into a Counter so we can conveniently subtract the previously seen values. Write the new ones into the list and add them to the seen ones.
Try it online!
You could do the same with set union and difference operators. As sets are unordered the final list would need to be sorted. Again assuming d is the original dictionary.
s = set()
for k in d:
z = d[k]
d[k]= sorted(list(set(z).difference(s)))
s |= set(z)

Nested list elements match with new list, if list contain the same add - python

I have nested list like below
mylist=[['2','3','100', '7'],[ '9', '13'],[ '21', '23', '25'],[],['9','24','45']]
i should compare with the new list if elements are present then print.
comp_list = ['2','3','100','9','13','25','45']
required output :
new_list=[['2','3','100'],['9','13'],['25'],[],['9','45']
i have something like below
for ele in mylist:
if ele in comp_list:
print(ele)
with this code the ele is not printed. can any one please help me to solve this. Thank you
You can try nested list comprehension as follow
mylist=[['2','3','100', '7'],[ '9', '13'],[ '21', '23', '25'],[],['9','24','45']]
comp_list = ['2','3','100','9','13','25','45']
new_list = [[y for y in i if y in comp_list] for i in mylist]
print(new_list)
If the comp_list is a large list it might be better to convert it to set before the comprehension because checking if a value is in a set is faster then in a list.
comp_set = set(comp_list)
new_list = [[y for y in i if y in comp_set] for i in mylist]
Output
[['2', '3', '100'], ['9', '13'], ['25'], [], ['9', '45']]
Below (classic nested for loop)
mylist = [['2','3','100', '7'],[ '9', '13'],[ '21', '23', '25'],[],['9','24','45']]
comp_list = ['2','3','100','9','13','25','45']
result = []
for entry in mylist:
tmp = []
for x in entry:
if x in comp_list:
tmp.append(x)
result.append(tmp)
print(result)
output
[['2', '3', '100'], ['9', '13'], ['25'], [], ['9', '45']]

How to convert python list to python dictionary with sequence

Can somebody tell me how to convert list1 to dic_list with all keys equal to the sequence of elements of the list and all values in dictionary equal to the elements in list split by ','?
input:
list1 = ['1,2,3','4,5,6','7,8']
expected output:
dic_list = {0:['1','2','3'],1:['4','5','6'],2:['7','8']}
I created a new list2:
list2 = []
for num in range(0,len(list1)):
list2.append(num)
dic_list = dict(zip(list2,list1))
But my output is:
dic_list = {0:'1,2,3',1:'4,5,6',2:'7,8'}
You can try this:
list1 = ['1,2,3','4,5,6','7,8']
final_list = {i:a.split(',') for i, a in enumerate(list1)}
Output:
{0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}
Or, using the builting dict function:
final_list = dict(enumerate(map(lambda x:x.split(','), list1)))
Output:
{0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}
You need to split the strings to form lists:
list1 = ['1,2,3', '4,5,6', '7,8']
dic_list = {k: v.split(',') for k, v in enumerate(list1)}
dic_list
output:
{0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}
You can enumerate to get the key and split the list with ',' to get desired value.
list1 = ['1,2,3', '4,5,6', '7,8']
Output = {key: value.split(',') for key, value in enumerate(list1)}
Output

Sorting list with strings & ints in numerical order

I'm currently dealing with the below list:
[['John', '1', '2', '3'], ['Doe', '1', '2', '3']]
I'm incredibly new to python, I'm wanting to order this list in numerical order (high - low) but maintain the string at the beginning of the list. Like this:-
[['John', '3', '2', '1'], ['Doe', '3', '2', '1']]
There will always be one name & integers there after.
I collect this list from a csv file like so:-
import csv
with open('myCSV.csv', 'r') as f:
reader = csv.reader(f)
your_list = list(reader)
print(sorted(your_list))
Any help is much appreciated. Thanks in advance..
Iterate over the list and sort only the slice of each sublist without the first item. To sort strings as numbers pass key=int to sorted. Use reverse=True since you need a reversed order:
>>> l = [['John', '1', '2', '3'], ['Doe', '1', '2', '3']]
>>>
>>> [[sublist[0]] + sorted(sublist[1:], key=int, reverse=True) for sublist in l]
[['John', '3', '2', '1'], ['Doe', '3', '2', '1']]

How to insert an item into a sublist if sublist is a certain length?

If sublist is 4 items, keep, if list is 3 items insert "Null" into the third place of the sublist. A for loop with a conditional "if" would do it, but it's pretty slow. Is there any faster method?
lst = [['4','4','4','4'],['3','3','3'],['1','42','','4'],['1','2','3']]
Desired_List = [['4','4','4','4'],['3','3','Null','3'],['1','42','5','4'],['1','2','Null','3']]
What I have, which doesn't work for some reason I don't understand:
Desired_List = []
for sublist in lst:
if len(sublist) == 3:
Desired_List.extend(sublist.insert(3,"Null"))
else:
Desired_List.extend(sublist)
This is really slow as I'm doing this to a large list. Are there any faster methods?
if you already change lst consider just using it instead of creating a new list Desired_List, simply do:
>>> for sublist in lst:
... if len(sublist) == 3:
... sublist.insert(2,"Null")
...
>>> lst
[['4', '4', '4', '4'], ['3', '3', 'Null', '3'], ['1', '42', '', '4'], ['1', '2', 'Null', '3']]

Categories