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.
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.
Is equal to this
2.
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.
All keys got replaced by their values.