r/learnpython • • Oct 02 '24

'for x, y in dictionary.items():'

1)Im confused. How does python recognize that x and y aren't some random variables but seems to somehow realize exactly that x and y are irrelevant placeholders that it should use as 'key' and 'value'?

Whenever it encounters 'in dictionary.items()' and 'for x, y' before that, is python preprogrammed to understand im not talking about random variables but keys?

2) Is this command just essentially telling it 'for key, a value is attached in x dictionary'? Like, yeah, no shit. Thats what a dictionary is. Why would I need to type this and not be able to just mention the dictionary and simply use':' to create a block from there?

Take this for example:

sequences = {'AGC': 'ATG', 'GGG': 'CCC'}

string7 = 'AGCAGCAAGGG'

string8 = string7

for a, l in sequences.items():

value string8 = string8.replace(a, l)

This is the method chat GPT suggested for replacing segments of a string using a dynamic dictionary.

Why cant I just bring up the dictionary name and essentially tell python that for a specific string, I want it to replace every key it encounters with its value, based on the dictionary I brought up?

Sorry for any crankiness, I've been asking chatGPT for an hour straight to explain this and I am just not able to understand.

0 Upvotes

43 comments sorted by

View all comments

Show parent comments

1

u/toofarapart Oct 03 '24

I’m sorry , I’m confused in by your examples. There were no ‘a’ or ‘l’ in the examples you brought up.

Same with the second example. There are no ‘a’.

Is your confusion about where a comes into existence since we never do a = "some value"?

-5

u/avagrantthought Oct 03 '24

I’m confused why I have to bring up the concept of keys and values to python in the first place. What exactly is the line “for a, l in sequence.items():” do for me here?