#πŸ”’ list comprehension with dictionaries

178 messages Β· Page 1 of 1 (latest)

molten rune
#

why cant i do this:

# list using dictionary
d = {'Name': 'John',
     'Grades': [100, 80, 20, 100]}
myList = [g for g in d[g]]

and yet this is a thing that works:

d = {'Name': 'John',
     'Grades': [100, 80, 20, 100]}
for g in d:
    print(d[g])
signal pendantBOT
#

@molten rune

Python help channel opened

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.

fathom sparrow
molten rune
#

g is just an iterable

fathom sparrow
molten rune
#

it doesnt need to be defined

signal pendantBOT
#

@fathom sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

['John', [100, 80, 20, 100]]
fathom sparrow
#

it works now

#

!e d = {'Name': 'John',
'Grades': [100, 80, 20, 100]}
for g in d:
print(d[g])

signal pendantBOT
#

@fathom sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | John
002 | [100, 80, 20, 100]
fathom sparrow
#

yup

fathom sparrow
molten rune
#

ah so i need the d[g] at the start

fathom sparrow
#

u r referring to it

#

without defining g

molten rune
#
d = {'Name': 'John',
     'Grades': [100, 80, 20, 100]}
for g in d:
    print(d[g])
#

g isnt defined here either

turbid copper
#

the loop defines g

#

there's more ways to assign data to a variable than just =

#

a for loop is one of those ways

molten rune
#

i dont really get why it works when u do d[g] for g in d

turbid copper
#

because that's the syntax of a list comprehension

slender rover
#

it will make your work done

turbid copper
#

<expression> for <variable> in <iterable>

fathom sparrow
#

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?

molten rune
#

yes i do in that loop

slender rover
#

no like what do you want to do ?

turbid copper
#

the actual outcome here isn't important

slender rover
turbid copper
molten rune
#

read the docs? lol...

turbid copper
#

They're here to discuss this with people

molten rune
#

so in the for loop the stuff on the left is the variable and the stuff on the right is the experssion?

slender rover
turbid copper
slender rover
fathom sparrow
#

@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

turbid copper
#

green is the expression, blue is the variable, orange is the iterable

slender rover
turbid copper
fathom sparrow
slender rover
molten rune
slender rover
turbid copper
#

comprehension syntax can take a bit of getting used to since the expression comes first

molten rune
#

does it work the same way with dictionary comprehension?

turbid copper
#

yes except it allows for k:v syntax as the expression

molten rune
#

key:value right

turbid copper
#

!e

d = {'Name': 'John',
     'Grades': [100, 80, 20, 100]}

upper_dict = {k.upper():v for k, v in d.items()}
print(upper_dict)
signal pendantBOT
#

@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.

{'NAME': 'John', 'GRADES': [100, 80, 20, 100]}
turbid copper
#

yes

#

this example will make all the keys uppercase strings

#

k.upper():v is the expression in this example

molten rune
#

can you use zip when iterating in a list comprehension?

turbid copper
#
d = {'Name': 'John',
     'Grades': [100, 80, 20, 100]}

upper_dict = {}

for k, v in d.items():
    upper_dict[k.upper()] = v

print(upper_dict)
molten rune
#

for like tuples

turbid copper
#

if it works in a for loop, it will work in a list comp

molten rune
#

ok perfect

molten rune
turbid copper
#

yup!

molten rune
#

at the end?

turbid copper
#

No, it would be the expression

molten rune
#

or is that considered an expression?

#

ah

turbid copper
#

you can use just an else at the end of the list comp

#

it's a great way to filter things

molten rune
#

but if u wanna do ternary it has to be at the start

turbid copper
#

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)
signal pendantBOT
#

@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.

['apples', 'apricots']
turbid copper
#

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)
signal pendantBOT
#

@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.

['apples', 'apricots']
turbid copper
#

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

turbid copper
#

!e

items = ['apples', 'bananas', 'apricots', 'cherries']

a_items = [item if item[0] == 'a' else '<REMOVED>' for item in items]
print(a_items)
signal pendantBOT
#

@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.

['apples', '<REMOVED>', 'apricots', '<REMOVED>']
molten rune
#

isnt the first index of a list the whole string

#

not just the first letter?

#

wouldnt item[0] be apple

turbid copper
#

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

molten rune
#

hmm ok wait but

#

when u iterate through a list arent u iterating through each full item in the list?

turbid copper
#

yes

#

for item in items

#

!e

items = ['apples', 'bananas', 'apricots', 'cherries']

for item in items:
    print(item[0])
signal pendantBOT
#

@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | a
002 | b
003 | a
004 | c
turbid copper
#

!e

items = ['apples', 'bananas', 'apricots', 'cherries']

print([item[0] for item in items])
signal pendantBOT
#

@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.

['a', 'b', 'a', 'c']
molten rune
#

!e

list ['help', 'im', 'so', 'lost']
for i in list:
  print(list[i])
signal pendantBOT
#

@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
molten rune
#

!e

list ['help', 'im', 'so', 'lost']
for i in list:
  print(i)
turbid copper
#

you don't really ever use [i] unless you're using range/enumerate

signal pendantBOT
#

@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
turbid copper
#

you don't have =

molten rune
#

omg

#

lol

#

yeah

#

i know

turbid copper
#

and I really recommend not naming a variable list

molten rune
#

T_T

#

!e

list1 = ['help', 'im', 'so', 'lost']
for i in list:
  print(list[i])
signal pendantBOT
#

@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
turbid copper
#

There's no rush when it comes to programming. Take your time to think about it

molten rune
#

ok im done

#

u get what im trying to do LOL

turbid copper
#

I don't

#

because that's invalid

molten rune
#

!e

list1 = ['help', 'im', 'so', 'lost']
for i in list:
  print(i)
signal pendantBOT
#

@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
molten rune
#

!e

list1 = ['help', 'im', 'so', 'lost']
for i in list1:
  print(i)
signal pendantBOT
#

@molten rune :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | help
002 | im
003 | so
004 | lost
molten rune
#

oh

#

i get it now

turbid copper
#

that's basically no different from my last example

#

i is the elements of the list

#

not the index

molten rune
#

when u get the first indx of the iterable its the first letter

turbid copper
#

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

slender rover
#

i is basically a variable for the looping condition πŸ˜‹ and list1 is the thing which it is looping in !

turbid copper
#

it's a variable

slender rover
#

yes

#

corrected it ^^

molten rune
#

!e

list1 = ['help', 'im', 'so', 'lost']
for i in list1:
  print(i[0])
signal pendantBOT
#

@molten rune :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | h
002 | i
003 | s
004 | l
slender rover
#

@molten rune see ! πŸ˜‹

turbid copper
#

!e

list1 = ['help', 'im', 'so', 'lost']
for i in range(len(list1)):
  print(list1[i])
signal pendantBOT
#

@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | help
002 | im
003 | so
004 | lost
turbid copper
#

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])
signal pendantBOT
#

@turbid copper :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | h
002 | i
003 | s
004 | l
turbid copper
#

In this case, we'd still need the [0] to access the first letter

molten rune
#

or with enumerate

turbid copper
#

yeah, no one will really use range(len(something)) professionally

#

unless you have a very specific reason

molten rune
#

is that always referred to as zip?

turbid copper
#

no, zip() is a zip

#

x, y is "multiple assignment" or "unpacking"

#

zip returns something that is capable of being unpacked

molten rune
#

@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

turbid copper
molten rune
#

[::2] ?

#

like that?

turbid copper
#

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])
signal pendantBOT
#

@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
molten rune
#

would enumerate work intead of range(len)?

turbid copper
#

no because enumerate doesn't have step

molten rune
turbid copper
signal pendantBOT
#
Python help channel closed

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.