Reputation: 187
I have a dictionary adict:
a={"good":2, "bad":-2}
a list with sublist of strings b:
b=[["how", "are", "good"],["bad", "BAD", "hello"]]
and a list of integers which is the same length as list b and is a score of each sublist of b:
c=[2, -4]
I need to assign the score of the sublist to the words in b that do not appear i the keys of a It should create a new dictionary as follows:
{{"how":2, "are":2},{"hello":-4}}
I have tried the following code but it does not work:
for sublst in b:
for i in sublst:
if i.lower() not in a.keys():
newdict=dict(zip(sublst, c))
Upvotes: 1
Views: 54
Reputation: 1157
Your code goes wrong at the zip line. Firstly,
sublist = [['how', 'are', 'good']
['bad', 'BAD', 'hello']]
while
c = [2, -4]
(sublist, c) works for the first two elements and not the elements satisfying the condition. To make this work, a different list has to be made consisting of
[['how', 'are'], ['hello']]
But this fails to zip the values because zip does not work on list of lists. So the solution to this problem comes out to store the c[i] value for the ith element of b. If any sub-element satisfies the condition, update the dictionary, otherwise keep on iterating and changing the value of c[i]. This method is implemented as follows :-
dic = {}
for i in range(len(b)):
score = c[i]
for j in b[i]:
if j.lower() not in a.keys():
dic.update({j : score})
Upvotes: 1
Reputation: 88275
Here's one way using a dictionary comprehension. Note that dictionaries are unhashable, so you cannot have a set of dictionaries. You could have the result be a list of dictionaries instead as bellow:
k = a.keys()
[{w:s for w in l if w.lower() not in k} for l,s in zip(b,c)]
# [{'how': 2, 'are': 2}, {'hello': -4}]
Upvotes: 1
Reputation: 559
a={"good":2, "bad":-2}
b=[["how", "are", "good"],["bad", "BAD", "hello"]]
c=[2, -4]
new_list = []
for i in range(len(b)):
value = c[i]
d= {}
for word in b[i]:
if(word.lower() not in a.keys()):
d[word] = value
new_list.append(d.copy())
print(new_list)
output:
[{'how': 2, 'are': 2}, {'hello': -4}]
Upvotes: 1