-2

I am trying to create multiple lists from a dictionary. For example:

dict_ = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
list_1 = [k for k, v in dict_.items()]
list_2 = [v for k, v in dict_.items()]

The above works but I am trying to find out if there is a single liner that would create both list_1 and list_2 instead of repeating the same "for" loop twice?

Tom Cider
  • 181
  • 1
  • 1
  • 11
  • You can do `list_1 = list(dict_.keys())`, `list_2 = list(dict_.values())`. Alternatively `list_1 = list(dict_)` – alani Oct 07 '20 at 19:35
  • If you really want a one-liner, you can of course use `list_1, list_2 = .... , ....` but I'm not sure whether that improves the code. – alani Oct 07 '20 at 19:37
  • If you want to use the same loop (which is good), why you feel like you need it to be in one line? What's wrong with a regular `for` loop? – Tomerikoo Oct 07 '20 at 19:37

2 Answers2

3
list_1, list_2 = list(dict_.keys()), list(dict_.values())
  • or you could use a single listcomp
list_1, list_2 = [list(tup) for tup in zip(*dict_.items())]
list_1, list_2 = map(list, zip(*dict_.items()))

but readability counts and simple is better than complex so the two separate lines are probably a better approach

Chris Greening
  • 510
  • 5
  • 14
2
dict_ = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
list_1, list_2 = list(dict_.keys()), list(dict_.values())
Sep
  • 347
  • 3
  • 13