intersection of lists called from defaultdict(list) - python

I would like to find the intersection of lists that are stored within the defaultdict(list) container. Here is my dictionary, 'd' a list of lookup values, 'my_list':
d = { a: ['1', '2', '3'],
b: ['3', '4', '5'],
c: ['3', '6', '7']
}
my_list = ['a', 'b']
I would like to return the intersection of the lists. Based on a previous post I tried the following but get an error: TypeError: unhashable type: 'list'
set.intersection(*map(set,d[my_list]))
any suggestions would be welcome.
thanks,
zach cp

The problem is that you are trying to access d[my_list] – a list is not a vlaid dictionary key. One alternative:
set.intersection(*(set(d[k]) for k in my_list))

Related

Split array based on value

I have an array:
foo = ['1', '2', '', '1', '2', '3', '', '1', '', '2']
¿Is there any efficient way to split this array into sub-arrays using '' as separator?
I want to get:
foo = [['1', '2'], ['1', '2', '3'], ['1'], ['2']]
In one line:
[list(g) for k, g in itertools.groupby(foo, lambda x: x == '') if not k]
Edit:
From the oficial documentation:
groupby
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).
The key I generate can be True, or False. It changes each time we find the empty string element. So when it's True, g will contain an iterable with all the element before finding an empty string. So I convert this iterable as a list, and of course I add the group only when the key change
Don't know how to explain it better, sorry :/ Hope it helped
Create a list containing a single list.
output = [[]]
Now, iterate over your input list. If the item is not '', append it to the last element of output. If it is, add an empty list to output.
for item in foo:
if item == '':
output.append([])
else:
output[-1].append(item)
At the end of this, you have your desired output
[['1', '2'], ['1', '2', '3'], ['1'], ['2']]

How do I extract index 0 of each list with Python?

I have the following list named "rows":
[['1', 'Peter', 'Cookies'], ['2', 'Sarah', 'Chocolate'], ['3', 'Daria', 'Lollies']]
I'm trying to store the elements at index 0 within each list in a variable called ID with set comprehension but am struggling.
I've tried the following:
ID = {[row[0] for row in rows]}
but get the error:
unhashable type list
I need to find a solution by using list comprehension.
THe error : unhashable type list is because you are trying to use a list as a key in a dictionary.
Try this to get the first element of each list.
ID = [row[0] for row in rows]
# ['1', '2', '3']
Code:
import numpy as np
rows = [['1', 'Peter', 'Cookies'], ['2', 'Sarah', 'Chocolate'], ['3', 'Daria', 'Lollies']]
ID = [rows[row][0] for row in range(len(rows))]
ID
Output:
['1', '2', '3']

python list of lists to firestore

I have a list that contains lists. I want to save it in firestore under a map that exists
list:
[['1', 'B'],
['5', 'E'],
['7', 'J']]
Output needed in firestore:
letter_count (map)
1:'B'
5:'E'
7:'J'
Any help?
It is not possible to store lists within lists in firebase, unfortunately (more info on that here: https://stackoverflow.com/a/59068112/8612435). What you can do is convert that list into a dictionary and pass that data into firebase instead:
# convert to dictionary
mydict = {}
for i in range(len(mylist)):
mydict[mylist[i][0]] = mylist[i][1]
print(mydict)
# push to firebase
db.collection('collection-name').document('document-name').set({'letter_count': mydict})
(Note: I took inspiration in multidimensional list conversion to dictionary through this post: convert multidimensional list into dictionary python)
Convert list into dictionary before you update it.
letter_case = {x[0]: x[1] for x in [['1', 'B'], ['5', 'E'], ['7', 'J']]}
print(letter_case)
Use update() to add if the list is not existing in document and update the field if it is existing, for example:
UPDATE:
convert into dictionary based on #Sabari's answer:
letter_case = {x[0]: x[1] for x in [['1', 'B'], ['5', 'E'], ['7', 'J']]}
doc_ref = db.collection(u'testcol').document(u'testdoc')
doc_ref.update({'letter_count': letter_case })

how do I convert the first part of JSON into an array python?

example
{'1':'e1','2':'e2','3':'e3'}
I am wondering if there is a way to isolate the name of the variables into an array of ['1','2','3'], in python.
All you need is list(d)
d = {'1':'e1','2':'e2','3':'e3'}
print(list(d)) # -> ['1', '2', '3']
In python: if d = {'1':'e1','2':'e2','3':'e3'}, then list(d.keys()) will give you ['1', '2', '3'].

converting nested list into a dictionary

b = [['a', '1'], ['b', '2'], ['c', '3']]
c = {}
for i in range(len(b)):
m = i[0]
c[m] = i[1]
My goal is to make the nested list b into a dictionary. However, I keep getting an error saying
TypeError: 'int' object is not subscriptable
Try this:
b = [['a', '1'], ['b', '2'], ['c', '3']]
d={}
for i in b:
d[i[0]]=i[1]
I'll explain the main issue with your code. But bottom line, best to use a dict comprehension:
{k:v for k, v in b}
# {'a': '1', 'b': '2', 'c': '3'}
Or just:
dict(b)
Your code as is will throw an error:
TypeError: 'int' object is not subscriptable
To understand why, try for i in range(len(b)): print(i). You'll see that your loop iteration values are just the index values of b, not the lists stored in b.
So doing i[0] won't work, since i is just an integer. What you want is more like b[i][0]. But there are easier ways to do that.
In particular, try instead: for i in b: print(i).
You'll see that now your iterations are putting each list inside b into i, and then you can do m = i[0] as planned. After that, your code will work, storing each dict value (i[1]) in each dict key (m):
for i in b:
m = i[0]
c[m] = i[1]
Note: While it is convention to use i when keeping track of index values, it's not really best practice (for that same reason) to use i for other kinds of iteration values. To avoid confusing your future self, use x or even current_list instead of i as your loop iterator name in situations like this. (But really, I'd advise just using the simpler alternatives I started out with at the top of this post.)
The issue is you are attempting to index into an integer i as if it was a list. I think you meant b[i][0] (this says: give me the 0-th item of the i-th item in b).
This is a little easier:
b = [['a', '1'], ['b', '2'], ['c', '3']]
d = dict(b)
print(d)
Output:
{'a': '1', 'b': '2', 'c': '3'}

Categories