-3

guys. Can you explain to me where can I find information about for loops in lists and dictionaries like this:

friendships = {i["id"]: ['Joe'] for i in users}

When I try to search in the Google "for loops in lists and dictionaries" it just gives me sites where information is only about a normal for loop like this:

for i in x: et cetera

I hope you'll help me :)

  • 3
    They are called "list comprehensions" and "dict comprehensions". – interjay Aug 15 '23 at 11:46
  • 2
    On docs.python.org I found about [list comprehension](https://docs.python.org/3/reference/expressions.html#index-12) in less than a minute. – destructioneer Aug 15 '23 at 11:52
  • 1
    Does this answer your question? [What does "list comprehension" and similar mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-and-similar-mean-how-does-it-work-and-how-can-i) – JonSG Aug 15 '23 at 13:26
  • @destructioneer Yes, it can be found in the documentation - if one knows what to search for. On the other hand the explanation for [list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) is in one of the first chapters of the tutorial. – Matthias Aug 15 '23 at 14:07
  • 1
    This is a dictionary comprehension. The value of *friendships* will depend on what *users* refers to. Unfortunately you haven't shown *users* or your expected output – DarkKnight Aug 15 '23 at 14:19
  • @Matthias I was searching for `for`, and found a reference for the statement and one for the comprehension. – destructioneer Aug 16 '23 at 07:21

1 Answers1

-2

I believe you have something wrong with users list:

input: { i['ID'] : 'JOE' for i in [{'ID':1},{'ID':2}]}

output: {1: 'JOE', 2: 'JOE'}

It is called list comprehension

JohnyCapo
  • 170
  • 10