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

22

u/Lewri Oct 02 '24 edited Oct 02 '24

The dictionary .items() method returns a view of the dictionary as key value tuples. That view is iterable, meaning you can iterate through it and each iteration you get a tuple, containing a key value pair. When you tell it to take that tuple (which being a key value pair, contains two items) and assign it to two variables, it is unpacking them.

That is to say, dictionary.items() returns something similar (though with under-the-hood differences) to [('ACG', 'ATG'), ('GGG', 'CCC')]. When you iterate through it (using a loop), the first iteration gives ('ACG', 'ATG') and the second iteration gives ('GGG', 'CCC'). For each of those, there is two objects inside, which you want to unpack and so you are unpacking them to the variables a and l.

This is essentially the same as doing:

sequences = [('ACG','ATG'),('GGG','CCC')]
for a, l in sequences:
    string8 = string8.replace(a, l)

Similarly:

sequences = {'AGC': 'ATG', 'GGG': 'CCC'}
for a in sequences:
    string8 = string8.replace(a, sequences[a])

(which is the way I would personally iterate through a dictionary)

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?

Because you could pass any iterable object into a python for loop. It doesn't need to be a dictionary, and even if it was a dictionary it might be different from your dictionary and the user might want to iterate through it in a different way than from what you want. So you have to tell Python what to do.

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

Stop asking chatGPT to hallucinate things for you and instead go read tutorials and play around with the code. Go through things line by line to see what they do and experiment with them.

-9

u/avagrantthought 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’.

because you could pass

Yeah but python understands that I’m using a dictionary type variable when I type it in, if I already defined the name assigned to a dictionary, to a dictionary, no?

The rest of your comment made perfect sense to me, thanks

7

u/backfire10z Oct 03 '24 edited Oct 03 '24

With regards to “a” and “l” (or “x” and “y”), what we’re saying is that it essentially does the following:

go through all the items in mydict:
    x = the_key
    y = the_value
    # your code here

There’s a lot that goes on in the background, but Python basically does the assignment for you (x = …, y = …).

Writing “for x, y in mydict.items()” is just how you tell Python to do the above. The language then reads “for x, y in dictionary.items()” and translates it a few times according to how the language’s syntax is defined and eventually reaches the point where it is assigning the name “x” and the name “y” to the key and value every time it loops. You get a shortcut by just typing “for x, y in mydict.items()” because Python is nice and created specifically so things like this can be typed quickly.

Truly, the answer you’re looking for here is how Python is interpreted/compiled into actual executable code. https://github.com/python/cpython/blob/main/InternalDocs/compiler.md

-8

u/avagrantthought Oct 03 '24 edited Oct 03 '24

I see.

I don’t under why would I want it to go through my dictionary.

The only thing I want for python to do regarding my dictionary, is replace any characters in a random string that are the same as a key in my dictionary, and to replace them with a value, based* of of my dictionary.

Are you saying that I first have to tell it to go through my dictionary?

I am sorry for the trouble but I don’t understand why.

When I bring up my dictionary, shouldn’t python already understand I’m referencing a ‘list’ of keys and values?

When I bring up a list, I don’t have to tell python im referencing objects inside that list.

Again, sorry for the trouble

4

u/backfire10z Oct 03 '24 edited Oct 03 '24

Ahh I see. In order to do that, at some point you’ll have to either loop through the string or the dictionary. There is no magic method to just wave your hands and say “replace all these with all those” via a dictionary that I know of.

Yes, the dictionary is a list of keys and values; Python knows this. However, it’s that middle part — replace instances of the keys in your string with their respective values — that cannot be done in 1 clean statement.

There is 1 real way to do this: find every instance of a dictionary key in your string and replace it. That can be done either on the string side or the dictionary side:

  • Loop through the string. For every 3 characters encountered, check if those 3 characters exist as a key in the dictionary and replace them with the respective value. This seems to be what you’re asking about.

  • Loop through the dictionary. For every key, look for each occurrence of that key in your string and replace it with the respective value. This is what chatGPT gave you

Both methods accomplish the same goal defined above, just in slightly different ways. You can use every 3 character sequence in the string and check if there’s a corresponding translation. You can alternatively look at every key, then find and replace every instance of that key in the string with the value.

In terms of efficiency, probably the second method (the one chatGPT gave you) is more efficient at times, but this delves into how strings work and depends on the string and dictionary sizes.

1

u/avagrantthought Oct 03 '24

Thanks for your time.

I am a bit confused by what the second option is.

Is it essentially creating proxies/placeholders for the key and values variables in the dictionary, and assigning them inside the replacement function and essentially scanning the string for them?

3

u/backfire10z Oct 03 '24 edited Oct 03 '24

Mostly correct. It does not create proxies/placeholders. It just gives them a name so that you can refer to them in your code. Here:

mydict = {“key1”: “value1”}

We have a variable that allows you to access a dictionary. We say the dictionary is assigned to the variable. Let’s represent this with an arrow:

mydict —> {“key1”: “value1”}

Now, when we want to access the value, what do we do?

val = mydict[“key1”]

What (to my understanding) you think it is doing is the following:

mydict —> {“key1”: “value1”}
val —> “value1”

What is actually occurring is:

mydict —> {“key1”: “value1”}
                                        ↑
                                       val

You can see that this isn’t a proxy. It’s the exact same object. We’re just giving it another name by which we can refer to it.

It’s like if a baby’s name is “John” and you also call the baby “Sweetie pie”. You have not created a new baby in doing so. It is still the same baby.

In Python, it is possible to create a copy, but typically this is done either explicitly by the programmer or implicitly because it’s required for the code to work as expected.

In the loop, you have:

dictionary —> {“key1”: “value1”, “key2”: “value2”}
                               ↑           ↑
                                x            y

dictionary —> {“key1”: “value1”, “key2”: “value2”}
                                                           ↑           ↑
                                                            x            y

1

u/avagrantthought Oct 03 '24

Thanks for the explanation, I appreciate it. Although, that wasn’t what I meant with the val example. I believe I understand what you meant with the val. val takes the place of anything that is in the value part of any couple in the list, no?

The little box you wrote below is very much appreciated but I think the last part is a bit broken.

You really don’t have to reply anymore because I don’t want to waste any time, but even though I believe I’ve understood what you commented here, I still don’t see how it connects to the example I gave in my post. Again, that’s probably because of me and being sleep deprived, so I don’t expect you to waste anymore time. Thanks for elaborating and helping me understand better.

1

u/backfire10z Oct 03 '24 edited Oct 03 '24

Oh rip the final box haha. It was meant to illustrate what the loop does.

for x, y in dictionary.items()

does the assignment for you. The for loop goes:

  • x points to the first key, y points to the first value

  • x points to the second key, y points to the second value

  • x points to the third key, y points to the third value

It isn’t creating a new dictionary, it isn’t making any new objects. It’s just giving you access to every single key and value one at a time. This is the only way for you to tell Python to replace key with value in your string, it has to be done one at a time (like I explained the 2 approaches in my previous comment).

The key and the value exist somewhere. The for loop just says “give them to me one at a time.” There is no way to slap the dictionary on top of the string and magically have all instances of every key replaced with its respective value.

→ More replies (6)

2

u/smurpes Oct 03 '24

The map function would be able to replace the values without explicitly iterating. Regex could do this too by generating the regex string from the dict.

2

u/backfire10z Oct 03 '24

I don’t see how map is any different: the question would still be the same, as it still iterates over the dictionary and would use the same destructuring syntax.

Yeah, I didn’t want to get into regex, but that would work too.

2

u/[deleted] Oct 03 '24

Now I see what your problem is, and it's not really about the names. It's that you want to jump up to another "dimension" and instead of replacing one thing with one thing, replace several things with several things.

This is a reasonable desire, and there are some rare languages where you can just do it. APL has a concept called rank polymorphism where you can perform an operation on a number, or a list of numbers, or a list of lists of numbers... and it'll "know" how to handle this. But most languages make you say hey, this operation is being applied across many things. The map function, for example. Or the list comprehension. Or the for loop.

Some of these require names for the intermediate steps, but that's not really the issue.

1

u/avagrantthought Oct 03 '24

Alright, thanks

1

u/Lewri Oct 03 '24

The only thing I want for python to do regarding my dictionary, is replace any characters in a random string that are the same as a key in my secondary, and to replace them with a value, based* of of my dictionary.

Are you saying that I first have to tell it to go through my dictionary?

As the saying goes: "there's a hundred ways to skin a cat".

You don't have to iterate through your dictionary, you could instead iterate through slices of your string, or you could probably do something more complicated using regex. But iterating through your dictionary is a simple solution to your problem.

When I bring up my dictionary, shouldn’t python already understand I’m referencing a ‘list’ of keys and values?

Sure, but then there's the question of what to do with them. Python doesn't know what you want it to do with these keys and values. You have to tell it.

When I bring up a list, I don’t have to tell python im referencing objects inside that list.

But you do. When you iterate through a list using a for loop, you have to tell it what you want to call the entries of the list while in the loop. This is the same as you are doing with this.

As I explained to you, dictionary.items() is, for all intents and purposes, a list.

Please, for the love of all that is holy, just take all the examples that everyone has given you and go play with them. Actually run things, try changing the code, experiment and see what happens.

1

u/avagrantthought Oct 03 '24

Alright, thanks

2

u/CyclopsRock 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’.

Those variable names can be literally anything. It might make more sense to consider this ..

my_list = ["Dog", "Cat", "Fish"]
for each_item in my_list:
    print(each_item)
# This will print Dog, then Cat, then Fish

The entire point of a "for" loop is that you are looping through a collection of items (aka an iterator) and assigning each one of these items to the same variable - in my case "each_item", but it could be "fuck_face_mcgoo" for all the difference it makes.

It's almost plain English already, but what it really means is "For each item in this list, do the same thing to it". Your choice of variable name (a or x or fuck_face_mcgoo) is so you can actually use that value in your code and thus "do the same thing to it" each time.

1

u/avagrantthought Oct 03 '24

Alright, I see, thank you.

So what exactly is the role of ‘for a, l in sequence.items:()’ in the role of replacing any text identified as a key in a string, with its variable, in the example code I gave in the body of this post?

1

u/CyclopsRock Oct 03 '24

There isn't one. It's the string you need to iterate through, not the dictionary. In basic English the process would be...

0) Make a new, empty string.

  1. Split your big string into 3-character chunks, if that's the length of the text you're identifying.

  2. For each of these chunks, check to see if there's a matching key in your dictionary.

3a) If there is, add this key's value to your new, empty string.

3b) If there isn't, add this chunk to your new string unaltered.

4) Once you're done your new string will be the same as the old string, only with the matching values swapped.

As you can see, none of this involves iterating through the dictionary. If the text you're searching for isn't actually split into 3-character chunks (it's not clear if this is the case) then you'll still need to iterate through the string (not the dict) but it becomes more complex.

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"?

→ More replies (1)

1

u/Lewri Oct 03 '24

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’.

What? I don't understand what you are saying here? I am just taking the loop from your post and explaining what it is doing and then showing alternatives that do the same thing...

Yeah but python understands that I’m using a dictionary type variable when I type it in, if I already defined the name assigned to a dictionary, to a dictionary, no?

Do you expect the for loop to have differently defined behaviour for each object type? And as I said, people may want to iterate through the dictionary in different ways. Also, as I showed you, you can just directly iterate through the dictionary without doing a .items() view and unpack, but iterating directly through the dictionary gives you the key, and so you then to get the values you have to do dict[key].

2

u/throwaway6560192 Oct 03 '24

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?

Because there's no built-in function to do that. You're writing essentially that functionality yourself.

6

u/cyberjellyfish Oct 03 '24

You'd spend less time being frustrated if you found a decent beginners python resource and worked through it. It's so much harder to piece bits together as you come across them than it is to just invest the time to build a solid foundation.

5

u/[deleted] Oct 02 '24 edited Oct 03 '24

When you put some name(s) on the left side of an equals, you're assigning to the name(s).

x, y = "hello", "world"

It's exactly the same thing when you put names in function parameters

def func(x, y):

or in a loop

for x, y in dictionary.items():

or in a few other situations. Python "knows" to use the concept of assignment. Whether or not there was anything associated with those names before, there is now.

If you're wanting to call the replace method on strings, then you might need stuff to put in there— what's getting replaced with what? Well, the names from the loop can help with that.

1

u/OkVariables Oct 02 '24 edited Oct 02 '24

The dict.items() method returns a list containing the key-value as tuple pairs of the dictionary.
If a "for loop" iterates over these tuples, it unpacks the tuples into the variables x and y.

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

for key,val in sequences.items():
    print(key,val)

Is equal to this

list_of_tuples = [('AGC','ATG'),('GGG','CCC')]

for x,y in list_of_tuples:
    print(x,y)

2.

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?

I don't get what you want to do here.

You can't replace keys because they are immutable. The way dictionaries work wouldn't make sense otherwise, since the hash for the key is unique.

What you could do is to create a new one with the desired changes.

new_sequences = {val: val for val in sequences.values()}

print(new_sequences)

> {'ATG': 'ATG', 'CCC': 'CCC'}

All keys got replaced by their values.

1

u/avagrantthought Oct 03 '24

I’m confused. There is no x and y in the list you made, no?

2

I likely misspoke. I meant replacing any section in a string that it recognises as a key, with its value.

Eg

genes: {‘AGC’ : ‘GGG’, ‘AGG : ‘CCC’}

DNA_string = ‘AGAGAAGCAGG’

And for it read the string and replace any sections that have the same text as any key in the dictionary, with their values

Which would turn the above into:

‘AGAGAGGGCCC’

1

u/OkVariables Oct 03 '24

I’m confused. There is no x and y in the list you made, no?

My bad. I named them key and val out of habit. But as you can see, it doesn't matter how you name them, whether it be key and val or x and y

1

u/audionerd1 Oct 03 '24
  1. dictionary.items() is a method that returns a list of tuples, each containing a key and value. 'x, y' in this case are variables assigned to the key and value pair via tuple unpacking. It doesn't matter what you name them. I usually go with for key, value in dictionary.items(): because it's more explicit.

  2. Your example is not formatted correctly, but it sounds like ChatGPT is suggesting looping through the items and using str.replace() to replace the keys (if they are present in the string) with the corresponding values in the dictionary, which sounds like an elegant solution to me.

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?

Isn't that literally what ChatGPT is suggesting with the for loop?

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

for key, value in sequences.items():
    string7 = string7.replace(key, value)

-3

u/avagrantthought Oct 03 '24

I’m sorry for not understanding but what is the purpose of ‘for key, value in dictionary.items():” in the below example?

Is it adding detail that I’m specifically referring to the keys and values of a specific dictionary instead of some random undefined variables of ‘key’ and ‘value?

How exactly is it doing that by essentially going “for tuple in x dictionary:” ?

1

u/audionerd1 Oct 03 '24

.items() is a method of the dictionary class which returns a list of tuples containing key/value pairs. Because the sequences variable contains a dictionary it has access to this method. sequences.items() in this case returns a list of two tuples, one for each dictionary entry, as follows:

[('AGC', 'ATG'), ('GGG', 'CCC')]

The for loop simply iterates through this list of two tuples, assigning them to the variables of your choice. Python doesn't know you're referring to keys and values, it only knows that there's a list of tuples. If that is still confusing you may need to learn more about for loops: https://www.w3schools.com/python/python_for_loops.asp

1

u/MidnightPale3220 Oct 03 '24

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?

The way ChatGPT told you to do it, is essentially telling python that.

Every programming language is like a toolbox.

You get spanners and wrenches, screwdrivers etc.

And then when you get to your car and need to change the front light, you gotta take the correct tools and apply them in the correct sequence.

If your toolbox had a gadget that simply changed lightbulbs by itself, that could be avoided, but since every brand and model of car can have different front lights, the manufacturers would need a whole lotta complicated tools for saving a person about half an hour every couple years. That would make no sense.

When you are creating a program you are essentially doing that yourself. You are creating a blueprint for applying correct tools in the correct sequence to satisfy your exact needs. After you do this, you can apply your blueprint wherever it fits. Voilà -- a car light changing gadget.

I hope the analogy is not too weird.

1

u/avagrantthought Oct 03 '24

Not at all, I appreciate you, thanks

2

u/commandlineluser Oct 02 '24

You may want to learn about iterators and tuple unpacking.

>>> next(iter(sequences.items()))
('AGC', 'ATG')
>>> x, y = next(iter(sequences.items()))
>>> print(f"{x=} {y=}")
x='AGC' y='ATG'

The for loop:

for x, y in sequences.items()
    print(f"{x=} {y=}")

Could be thought of as:

it = iter(sequences.items())

while True:
    try: 
        x, y = next(it)
        print(f"{x=} {y=}")
    except StopIteration:
        break

As for performing the multi-replace, I believe there is a specific algorithm for it: ahocorasick

It's not in Python stdlib, but there are various libraries on pypi.

import polars as pl

print(
    pl.select(pl.lit('AGCAGCAAGGG').str.replace_many(sequences)).item()
)
# 'ATGATGAACCC'

1

u/Adrewmc Oct 03 '24 edited Oct 03 '24

It’s just the syntax of

   for *tuple in sequence:

So for dictionaries you can use

   for key in dict: #.keys()
         print(key)
   for value in dict.values():
         print(value)

   for key, value in dict.items():
         print(key, value)
   for tup in dict.items():
         print(*tup)
         print(tup[0], tup[1])

.items() is a method of the dictionary type/class, so it’s built into Python to return an iterable of key, value pairs.

Because an iterable can return multiple things.

   points = [(1,2,3), (4,6,7), (8,7,4)]
   for x, y, z in points:
         print(x*y*z)

Because we can do that anywhere.

    x, y = 4, 6
    tup = 4,6
    x, y = *tup

  def reverse_tup(x,y): 
        return y, x

1

u/stuaxo Oct 03 '24

x and y ARE some variables.

But more importantly there are two of them and .items() gives back two things each iteration (a key and value from the dictionary), so they go into your variables which you happen to have named x and y.