-3

I have double for-loop and I would like to reformat it to dict comprehensions:

tests = {'var1': {'L': True, 'C': True},
         'var2': {'L': False, 'C': True},
         'var3': {'L': False, 'C': False}}

for feat, tags in tests.iteritems():
    for name, value in tags.iteritems():
        if value is True:
            print '{}, {}'.format(name, feat))
            obj = create_obj(type=name)
            run_method(feat, obj)

Should be easy?

emcek
  • 459
  • 1
  • 6
  • 17
  • 1
    You aren't creating a new dictionary; there's no use for a dict comprehension here. – chepner Feb 01 '16 at 16:56
  • I see, so I misunderstood list/dict comprehension, but if i leave only print statemant, it's working as @Kasramvd mention. – emcek Feb 01 '16 at 17:33

1 Answers1

1

Since you are printing a string you can use a list comprehension like following:

['{}, {}'.format(name, feat) for feat, tags in tests.iteritems() for name, value in tags.iteritems() if value]

And if you want to create a key-value pair from name and feat you can use a dict comprehension:

{name:feat for feat, tags in tests.iteritems() for name, value in tags.iteritems() if value}
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • and if I want execute some method instead of print: run_method(name, value)? – emcek Feb 01 '16 at 16:57
  • @emcek What you mean by executing some method? does it returns anything? if it returns a value you can replace `'{}, {}'.format(name, feat)` with your attribute which has been called like (`my_attr()`) if not it would be none. – Mazdak Feb 01 '16 at 17:00