-6
def items(dic):
     li = []
     for item in dic:
         it = (item, dic[item])
         li.append(it)
     return li

How I can convert this into list comprehension?

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
  • The animation in [this](https://stackoverflow.com/questions/18072759/list-comprehension-on-a-nested-list/45079294#45079294) answer Has been a great help to me. – quamrana Sep 19 '21 at 20:17
  • 2
    `list(dic.items())` – Peter Wood Sep 19 '21 at 20:18
  • 1
    `[(key, value) for key, value in dic.items()]` or `[item for item in dic.items()]` - I don't understand why everybody is answering with `(item, dic[item])`. Of course I will prefer @PeterWood suggestions but of course it's not a list comprehension. – buran Sep 19 '21 at 20:23

3 Answers3

0
def items(dic):
    return [(item, dic[item]) for item in dic]
Eladtopaz
  • 1,059
  • 1
  • 5
  • 20
-1

Like this:

li = [(item, dic[item]) for item in dic]
Honn
  • 646
  • 1
  • 15
-1

The direct translation of your code would be [(item, dic[item]) for item in dic], however in this case no list comprehension is required assuming that dic is a dict object - you could use list(dic.items()).

Oli
  • 2,270
  • 1
  • 9
  • 23