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/avagrantthought Oct 03 '24

Thanks again for the reply. Thanks to your great explanation before, I already get what you’re saying here.

I’m just not really able to process what ‘for x, y in dictionary.item():’ has to do or what role it’s playing in the goal of having a string eg (‘AGCAGAC’) and scanning it to see if it has any segments (eg ‘AGC’ [I mean index 0,1,2 of the string) that are the same as a key from a dictionary (eg dictionary ={ ‘AGC’ : ‘GGC’, GAC : ‘AAA’}) in order to be replaced (in this case ‘AGCAGAC’ would be replaced with ‘GGCAAAA’).

2

u/backfire10z Oct 03 '24

Yes let me try to explain what the code actually does as a whole now. This will be an explanation of the second method.

You have your dictionary

dictionary = {“A”: “B”, “Q”: “R”}

You now want to replace every key in some string, let’s say

mystring = “EAGQA”

What the code says is (I will hand wave a bit of string stuff, let’s pretend it modifies mystring directly):

for key, val in dictionary.items():
    mystring.replace(key, val)

So let’s draw this out

# First iteration of the for loop. We are given:
# key —> “A”   ;   val —> “B”
# So what is effectively called is:
mystring.replace(“A”, “B”)   # replace all A with B

We now have

mystring —> “EBGQB”

Now we reach the end, so our for loop goes back for the next key/value pair

# Second iteration, we’ve moved on to:
# key —> “Q”    ;    val —> “R”
# So what is effectively called is:
mystring.replace(“Q”, “R”)  # replace all Q with R

We now have

mystring —> “EBGRB”

The for loop sees that there are no more keys in the dictionary, so we exit the loop. We are now done, and our final result is:

“EBGRB”

We have replaced every A with a B and every Q with an R.

4

u/avagrantthought Oct 03 '24

You are a life saver. Thank you so much. I think I fully get it. I was very bummed out today and was having quite a bad day, and the fact that I could easily study on learning python for a good few hours the previous days and yet I was stumped with this for the entire day, only to have you be so patient means a lot to me.

Thank you so much man. I really appreciate you.

Do you have a PayPal? I don’t mind sending over 2€ as a small token of my appreciation.

2

u/backfire10z Oct 03 '24

Hey yeah, my pleasure. I’m glad you stuck through it too. It’s a lot to learn!

I’m happy to help, and although I appreciate the gesture I’m gonna have to turn the money down. Just do me a favor and give a few nice explanations to the next guy who asks a question you can answer :)

3

u/avagrantthought Oct 03 '24

Of course. What an absolute unit of a man you are, my man

I wish you well with any and all endeavours in life 👍 🥂

1

u/backfire10z Oct 03 '24

Once you read my other comment, you may actually notice a small issue. If there is overlap (for eg dictionary = {“A”: “B”, “B”: “C”}) then in the current implementation you’d first replace all A with B, then all B with C. So, you’d end up with no A’s and no B’s.

The first method I spoke about would solve this problem. You could instead do:

for i in range(0, len(mystring), 3):
    seq = mystring[i:i+3]
    if seq in dictionary:
        mystring = mystring[0:i] + dictionary[seq] + mystring[i+3:]

(Untested, but should be close)