Any value in a specific key in a python dictionary
In python I have a dictionary called
d = {('A', 'A', 'A'):1, ('A', 'A', 'B'):1, ('A', 'A', 'C'):1, ('A', 'B', 'A'): 2, ('A', 'B','C'):2, ...}.
Is there an easy way to change the values (like 10) for if the key is like ('A', 'A', _)
, where _
could any char be A~Z
?
So it will look like {('A', 'A', 'A'):10, ('A', 'A', 'B'):10, ('A', 'A', 'C'):10, ('A', 'B', 'A'): 2, ('A', 'B', 'C'):2, ...}
the end.
At the moment I am using a variable loop x
for ('A', 'A', x)
, but I am wondering if there are such keywords in python.
Thanks for the advice.
source to share
Just check the first two elements of each tuple, the last one doesn't matter unless you specifically want to make sure it's also a letter:
for k in d:
if k[0] == "A" and k[1] == "A":
d[k] = 10
print(d)
{('A', 'B', 'A'): 2, ('A', 'B', 'C'): 2, ('A', 'A', 'A'): 10, ('A', 'A', 'C'): 10, ('A', 'A', 'B'): 10}
If the last element should also be alpha, then use str.isalpha:
d = {('A', 'A', '!'):1, ('A', 'A', 'B'):1, ('A', 'A', 'C'):1, ('A', 'B', 'A'): 2, ('A', 'B','C'):2}
for k in d:
if all((k[0] == "A", k[1] == "A", k[2].isalpha())):
d[k] = 10
print(d)
{('A', 'B', 'A'): 2, ('A', 'B', 'C'): 2, ('A', 'A', '!'): 1, ('A', 'A', 'C'): 10, ('A', 'A', 'B'): 10}
No keyword where d[('A', 'A', _)]=10
will work, you can hack a functional approach using a map with python2:
d = {('A', 'A', 'A'):1, ('A', 'A', 'B'):1, ('A', 'A', 'C'):1, ('A', 'B', 'A'): 2, ('A', 'B','C'):2}
map(lambda k: d.__setitem__(k, 10) if ((k[0], k[1]) == ("A", "A")) else k, d)
print(d)
{('A', 'B', 'A'): 2, ('A', 'B', 'C'): 2, ('A', 'A', 'A'): 10, ('A', 'A', 'C'): 10, ('A', 'A', 'B'): 10}
Or including isalpha:
d = {('A', 'A', '!'):1, ('A', 'A', 'B'):1, ('A', 'A', 'C'):1, ('A', 'B', 'A'): 2, ('A', 'B','C'):2}
map(lambda k: d.__setitem__(k, 10) if ((k[0], k[1],k[2].isalpha()) == ("A", "A",True)) else k, d)
print(d)
source to share
How about something like this:
for item in d.keys():
if re.match("\('A', 'A', '[A-Z]'\)",str(item)):
d[item] = 10
This is a different method. Returns None in the console, but appears to update the values:
[d.update({y:10}) for y in [x for x in d.keys() if re.match("\('A', 'A', '[A-Z]'\)",str(x))]]
source to share