0

I have the following two lists
states = ('ab',['rose','cose'])
flowers = {'rose':0,'cose:0','mose:0'}

Now need the flowers dictionary to be changed to
flowers = {'rose':1,'cose:1','mose:0'}
after I loop th states

I tried this but some syntax seems to be a problem!

[flowers[i] = 1 for i in states[1] if i in flowers.keys()]

Help is really appreciated! I am not able to understand, I kept the expression first and the conditional in the last! :/

2
  • 1
    I hope your data structure makes sense in a wider context, because it doesn't at all from just what you've shown. There's no need for flowers to be a list, if you only ever care about the single dict value it contains. If you don't need the list, just reference the dict directly!
    – Blckknght
    Apr 15, 2018 at 1:20
  • Yes, thats my mistake I meant for it be a single dict not a list. Thanks.
    – Paul Alwin
    Apr 15, 2018 at 1:25

2 Answers 2

3

You shouldn't be using list comprehension for this problem, as you are modifying your existing list not making a new one.

for i in states[1]:
    flowers[0][i] += 1
flowers
>>>[{'rose':1,'cose':1,'mose':0}]

If you insist on list comprehension:

new_flowers = [{i:states[1].count(i) for i in flowers[0]}]
new_flowers
>>>[{'rose': 1, 'cose': 1, 'mose': 0}]

Note this doesn't modify your original dict of flowers but instead makes a new one.

2

You can use collections.Counter:

import collections
counter = collections.Counter(states[-1])
new_flowers = [{a:counter.get(a, b) for a, b in i.items()} for i in flowers]

Output:

[{'rose': 1, 'cose': 1, 'mose': 0}]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.