#π list comprehension with dictionaries
178 messages Β· Page 1 of 1 (latest)
@molten rune
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
how are u referring g without defining it
g is just an iterable
!e ```py
list using dictionary
d = {'Name': 'John',
'Grades': [100, 80, 20, 100]}
myList = [d[g] for g in d]
print(myList)```
it doesnt need to be defined
@fathom sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
['John', [100, 80, 20, 100]]
it works now
!e d = {'Name': 'John',
'Grades': [100, 80, 20, 100]}
for g in d:
print(d[g])
@fathom sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | John
002 | [100, 80, 20, 100]
yup
wot
ah so i need the d[g] at the start
it does
u r referring to it
without defining g
d = {'Name': 'John',
'Grades': [100, 80, 20, 100]}
for g in d:
print(d[g])
g isnt defined here either
the loop defines g
there's more ways to assign data to a variable than just =
a for loop is one of those ways
i dont really get why it works when u do d[g] for g in d
because that's the syntax of a list comprehension
it will make your work done
<expression> for <variable> in <iterable>
what u wrote was
d = {'Name': 'John',
'Grades': [100, 80, 20, 100]}
for g in d[g]:
print(g)```
if we convert ur list comp literally
see where the issue is?
yes i do in that loop
no like what do you want to do ?
They're just trying to understand the syntax
the actual outcome here isn't important
Very unhelpful.
read the docs? lol...
They're here to discuss this with people
so in the for loop the stuff on the left is the variable and the stuff on the right is the experssion?
u mean they want to change the syntax by dicsussing it πΏ
the stuff indented below the for loop is the expression
look do you know how the for loop works first ?

@slender rover if u arent interested in helping and only degrading OP, i suggest u stop msging instead
or go to a server that entertains degradation
wrong mention nvm i am trying to ! jst asking him if he knows for loop thing i would love to explain him the beauty of python.
You pinged the wrong user, but yes
oops π
True
ok this is immensily helpful lol
They'll ask if they need it
Emotional Damage...
comprehension syntax can take a bit of getting used to since the expression comes first
does it work the same way with dictionary comprehension?
yes except it allows for k:v syntax as the expression
key:value right
!e
d = {'Name': 'John',
'Grades': [100, 80, 20, 100]}
upper_dict = {k.upper():v for k, v in d.items()}
print(upper_dict)
@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.
{'NAME': 'John', 'GRADES': [100, 80, 20, 100]}
yes
this example will make all the keys uppercase strings
k.upper():v is the expression in this example
can you use zip when iterating in a list comprehension?
d = {'Name': 'John',
'Grades': [100, 80, 20, 100]}
upper_dict = {}
for k, v in d.items():
upper_dict[k.upper()] = v
print(upper_dict)
for like tuples
you can use whatever you want
if it works in a for loop, it will work in a list comp
ok perfect
can you use ternary operators inside our comprehensions?
yup!
at the end?
No, it would be the expression
you can use just an else at the end of the list comp
it's a great way to filter things
but if u wanna do ternary it has to be at the start
yes because it's an expression
!e
items = ['apples', 'bananas', 'apricots', 'cherries']
a_items = []
for item in items:
if item[0] == 'a':
a_items.append(item)
print(a_items)
@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.
['apples', 'apricots']
here's a basic for loop that filters out all items that don't begin with "a"
!e
items = ['apples', 'bananas', 'apricots', 'cherries']
a_items = [item for item in items if item[0] == 'a']
print(a_items)
@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.
['apples', 'apricots']
and here's the list comp equivalent
notice how the new list is shorter, because items have been filtered
if you were to use ternary, the resulting list would always have to be the same length
so many items...
!e
items = ['apples', 'bananas', 'apricots', 'cherries']
a_items = [item if item[0] == 'a' else '<REMOVED>' for item in items]
print(a_items)
@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.
['apples', '<REMOVED>', 'apricots', '<REMOVED>']
isnt the first index of a list the whole string
not just the first letter?
wouldnt item[0] be apple
no, items is the list. item is each individual string in the list
item[0] is the first letter of the string
it's common to use singular and plural variable names like this
plural for the list, singular for the individual item
hmm ok wait but
when u iterate through a list arent u iterating through each full item in the list?
yes
for item in items
!e
items = ['apples', 'bananas', 'apricots', 'cherries']
for item in items:
print(item[0])
@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | a
002 | b
003 | a
004 | c
!e
items = ['apples', 'bananas', 'apricots', 'cherries']
print([item[0] for item in items])
@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.
['a', 'b', 'a', 'c']
!e
list ['help', 'im', 'so', 'lost']
for i in list:
print(list[i])
@molten rune :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | for i in list:
004 | TypeError: 'type' object is not iterable

!e
list ['help', 'im', 'so', 'lost']
for i in list:
print(i)
you don't really ever use [i] unless you're using range/enumerate
@molten rune :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | for i in list:
004 | TypeError: 'type' object is not iterable
you don't have =
and I really recommend not naming a variable list
@molten rune :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | for i in list:
004 | TypeError: 'type' object is not iterable
There's no rush when it comes to programming. Take your time to think about it
!e
list1 = ['help', 'im', 'so', 'lost']
for i in list:
print(i)
@molten rune :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | for i in list:
004 | TypeError: 'type' object is not iterable
!e
list1 = ['help', 'im', 'so', 'lost']
for i in list1:
print(i)
@molten rune :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | help
002 | im
003 | so
004 | lost
that's basically no different from my last example
i is the elements of the list
not the index
when u get the first indx of the iterable its the first letter
it's only the index when you use range or enumerate
it's not the index
which is even more of a reason I don't recommend using i as a variable unless you're dealing with indices
i is basically a variable for the looping condition π and list1 is the thing which it is looping in !
It's not a condition
it's a variable
!e
list1 = ['help', 'im', 'so', 'lost']
for i in list1:
print(i[0])
@molten rune :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | h
002 | i
003 | s
004 | l
@molten rune see ! π
!e
list1 = ['help', 'im', 'so', 'lost']
for i in range(len(list1)):
print(list1[i])
@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | help
002 | im
003 | so
004 | lost
you're probably used to seeing it this way, using range
!e
list1 = ['help', 'im', 'so', 'lost']
for i in range(len(list1)):
print(list1[i][0])
@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | h
002 | i
003 | s
004 | l
In this case, we'd still need the [0] to access the first letter
yeah i am lol
or with enumerate
yeah, no one will really use range(len(something)) professionally
unless you have a very specific reason
when you refer to two things in like an x, y format
is that always referred to as zip?
no, zip() is a zip
x, y is "multiple assignment" or "unpacking"
zip returns something that is capable of being unpacked
@turbid copper hey is there a way to iterate through 2 items in a list a time
so like if a list has 10 numbers u iterate over it 5 times
Sure, you could use a step/slice
This is one of those cases that I would use range/len
!e
letters = 'abcdefghij'
step_size = 2
for i in range(0, len(letters), step_size):
print(letters[i:i+step_size])
@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ab
002 | cd
003 | ef
004 | gh
005 | ij
would enumerate work intead of range(len)?
forgot to tag
no because enumerate doesn't have step
is there a way to add items to an empty tuple?
No, tuples are immutable
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.
