r/learnpython • u/avagrantthought • 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.
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.
1
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
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
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.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 thesequencesvariable 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
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:
breakAs 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, x1
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.
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 variablesaandl.This is essentially the same as doing:
Similarly:
(which is the way I would personally iterate through a dictionary)
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.
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.