Print the last element in a dictionary in a set - python

I need to select the last element from the following output.
print(result)
[('ABC', 880, {0: 'A', 1: 'P', 2: 'O', 3: 'T', 4: 'S'}),
('CDE', 120, {0: 'S', 1: 'E', 2: 'N'}),
('EFG', 240, {0: 'G', 1: 'R'})]
Desired output:
[S,N,R]

Assuming a list l of tuples as input:
out = [list(t[-1].values())[-1] for t in l]
output: ['S', 'N', 'R']
To print:
print(*out, sep='\n')
output:
S
N
R

Maybe something like this?
alist = [
('ABC', 880, {0: 'A', 1: 'P', 2: 'O', 3: 'T', 4: 'S'}),
('CDE', 120, {0: 'S', 1: 'E', 2: 'N'}),
('EFG', 240, {0: 'G', 1: 'R'})
]
print([adict[max(adict)] for _, _, adict in alist])
Output:
['S', 'N', 'R']

Assuming you have a list of tuples and each tuple has three elements of which the last is a dictionary then you could do this:
list_ = [
('ABC', 880, {0: 'A', 1: 'P', 2: 'O', 3: 'T', 4: 'S'}),
('CDE', 120, {0: 'S', 1: 'E', 2: 'N'}),
('EFG', 240, {0: 'G', 1: 'R'})
]
for _, _, d in list_:
print(list(d.values())[-1])
Output:
S
N
R

Related

How can I change/swap value position is python dictionary?

I'm trying to make a cipher based on Ceaser Cipher, which instead of letters, I used numbers. for example, 1 = 'a', 2 = 'b' and so on.
This is the full code:
import string
dict = {}
message = input("Enter a message\n")
key = input("Enter a key\n")
encrypted = ""
for i, char in enumerate(string.ascii_lowercase):
#key is from 0 to 25
dict[i] = char
print(dict)
for val in message:
if val in dict:
encrypted += dict[val]
for key, value in dict.items():
if val == value:
encrypted += str(key + 1)
encrypted += " "
print(encrypted)
in print(dict), it prints the value of the key
For example:
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h'}
What I want to do is to change the value based on the key input
For example:
key = 'D3'
My desired output:
{0: 'd', 1: 'e', 2: 'f', 3: 'a', 4: 'b', 5: 'c', 6: 'g', 7: 'h'}
Is there any solution for this?
This solution works only for the first time that the value_of_interest is found within the dict. In your case example - that s not the case, but I am not sure whether a more generalized approach of your cipher (I don t really know what exactly this is) ought to have this considered beforehand.
my_dict={0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h'}
print(f'Init dict: {my_dict}')
key_list=list(my_dict.keys())
#let's say ... (please make a more generalized parsing method for swaper)
swaper='D3'
print(f'Input swaper: {swaper}')
value_of_interest=swaper[0].lower()
shift_=int(swaper[1])
new_dict={}
for counter,key in enumerate(key_list):
if my_dict[key]==value_of_interest :
if len(key_list)>=counter+shift_: #Added a method for checking whether there are enough keys within the dict - after the D value is found.
new_dict = {i:my_dict[key] for i,key in enumerate(key_list[counter:counter+shift_])}
for i,key in enumerate(key_list[0:counter]):
new_dict[shift_+i]=my_dict[key]
for key in key_list[counter+shift_:]:
new_dict[key]=my_dict[key]
else:
print(f'There are not more than {shift_} keys following the {value_of_interest} value')
print(f'Output dict: {new_dict}')
Output:
Init dict: {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h'}
Input swaper: D3
Output dict: {0: 'd', 1: 'e', 2: 'f', 3: 'a', 4: 'b', 5: 'c', 6: 'g', 7: 'h'}
In another case for example, Given the value of "B5" in the swaper variable, it gives:
Init dict: {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h'}
Input swaper: B5
Output dict: {0: 'b', 1: 'c', 2: 'd', 3: 'e', 4: 'f', 5: 'a', 6: 'g', 7: 'h'}
I assume 'd3' means starting from d you are switching 3 values to the left side. If that's the case, 'd2' will return the following output:{0: 'd', 1: 'e', 2: 'c', 3: 'a', 4: 'b', 5: 'f', 6: 'g', 7: 'h'}
See if this code will work, I wrote a loop and it allows you to customize your key every time. d is the initial dictionary and k is the 'D3' key.
def swipe(d,k):
start = k[0].lower()
num = int(k[1])
count = 0
for i in d:
if d[i] == start:
break
else:
count+=1
for i in range(count,count+num):
d[i-count], d[i] = d[i],d[i-count]
return d

Make all permutation combination and replace in string

I have dataframe column with strings, similar to:
'TCCTGTAAATCAAAGGCCAAGRG', 'GNGCNCCNGAYATRGCNTTYCC', 'GATTTCTCTYCCTGTTCTTGCA'
and I have a list of letter:
SNPs={}
SNPs["Y"] = ['C', 'T']
SNPs["R"] = ['A', 'G']
SNPs["N"] = ['C', 'G', 'A', 'T']
where every R needs to change to A/G and so on...
ex: TCCTGTAAATCAAAGGCCAAGRG
changes to TCCTGTAAATCAAAGGCCAAGAG and TCCTGTAAATCAAAGGCCAAGGG.
I want all permutation and combinations and the result in other column.
Please help me with the same.
import re, itertools
text = "GNGCNCCNGAYATRGCNTTYCC"
def getList(dict):
return list(dict.keys())
lsources = getList(SNPs)
ldests = []
for source in lsources:
ldests.append(SNPs[source])
#print(ldests)
# Generate the various pairings
for lproduct in itertools.product(*ldests):
#print(lproduct)
for i in text:
output = i
for src, dest in zip(lsources, lproduct):
# Replace each term (you could optimise this using a single re.sub)
output = output.replace("%s" % src, dest)
print(output)
this is my code..but I am not getting desired output
Try this:
>>> import itertools
>>> text = "GNGCNCCNGAYATRGCNTTYCC"
>>> SNPs={ "Y" : ['C', 'T'] , "R" : ['A', 'G'] , "N" : ['C', 'G', 'A', 'T']}
>>> text_tmp = ""
>>> dct = {}
>>> for idx, v in enumerate(text):
... if v in SNPs:
... dct[idx] = SNPs.get(v)
... text_tmp += f'_{idx}_'
... else:
... text_tmp += v
>>> text_tmp
'G_1_GC_4_CC_7_GA_10_AT_13_GC_16_TT_19_CC'
>>> dct
{1: ['C', 'G', 'A', 'T'],
4: ['C', 'G', 'A', 'T'],
7: ['C', 'G', 'A', 'T'],
10: ['C', 'T'],
13: ['A', 'G'],
16: ['C', 'G', 'A', 'T'],
19: ['C', 'T']}
>>> per_val = list(itertools.product(*dct.values()))
>>> per_key_val = list(map(dict,[zip(dct.keys(), p) for p in per_val]))
>>> per_key_val
[{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'C', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'C', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'G', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'G', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'A', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'A', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'T', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'A', 16: 'T', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'C', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'C', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'G', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'G', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'A', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'A', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'T', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'C', 13: 'G', 16: 'T', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'T', 13: 'A', 16: 'C', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'T', 13: 'A', 16: 'C', 19: 'T'},
{1: 'C', 4: 'C', 7: 'C', 10: 'T', 13: 'A', 16: 'G', 19: 'C'},
{1: 'C', 4: 'C', 7: 'C', 10: 'T', 13: 'A', 16: 'G', 19: 'T'},
...
]
>>> out = []
>>> for pkl in per_key_val:
... tmp = text_tmp
... for k,v in pkl.items():
... tmp = tmp.replace(f'_{k}_', v)
... out.append(tmp)
>>> out
['GCGCCCCCGACATAGCCTTCCC',
'GCGCCCCCGACATAGCCTTTCC',
'GCGCCCCCGACATAGCGTTCCC',
'GCGCCCCCGACATAGCGTTTCC',
'GCGCCCCCGACATAGCATTCCC',
'GCGCCCCCGACATAGCATTTCC',
'GCGCCCCCGACATAGCTTTCCC',
'GCGCCCCCGACATAGCTTTTCC',
'GCGCCCCCGACATGGCCTTCCC',
'GCGCCCCCGACATGGCCTTTCC',
'GCGCCCCCGACATGGCGTTCCC',
'GCGCCCCCGACATGGCGTTTCC',
'GCGCCCCCGACATGGCATTCCC',
'GCGCCCCCGACATGGCATTTCC',
'GCGCCCCCGACATGGCTTTCCC',
'GCGCCCCCGACATGGCTTTTCC',
'GCGCCCCCGATATAGCCTTCCC',
'GCGCCCCCGATATAGCCTTTCC',
'GCGCCCCCGATATAGCGTTCCC',
'GCGCCCCCGATATAGCGTTTCC',
'GCGCCCCCGATATAGCATTCCC',
'GCGCCCCCGATATAGCATTTCC',
'GCGCCCCCGATATAGCTTTCCC',
...
]
Update: (run on dataframe)
def rplc_per(text):
SNPs={ "Y" : ['C', 'T'] , "R" : ['A', 'G'] , "N" : ['C', 'G', 'A', 'T']}
text_tmp = ""
dct = {}
for idx, v in enumerate(text):
if v in SNPs:
dct[idx] = SNPs.get(v)
text_tmp += f'_{idx}_'
else:
text_tmp += v
per_val = list(itertools.product(*dct.values()))
per_key_val = list(map(dict,[zip(dct.keys(), p) for p in per_val]))
out = []
for pkl in per_key_val:
tmp = text_tmp
for k,v in pkl.items():
tmp = tmp.replace(f'_{k}_', v)
out.append(tmp)
return out
df = pd.DataFrame({'String': ['TCCTGTAAATCAAAGGCCAAGRG', 'GNGCNCCNGAYATRGCNTTYCC', 'GATTTCTCTYCCTGTTCTTGCA']})
df['all_per'] = df['String'].apply(rplc_per)
print(df)
Output:
String all_per
0 TCCTGTAAATCAAAGGCCAAGRG [TCCTGTAAATCAAAGGCCAAGAG, TCCTGTAAATCAAAGGCCAA...
1 GNGCNCCNGAYATRGCNTTYCC [GCGCCCCCGACATAGCCTTCCC, GCGCCCCCGACATAGCCTTTC...
2 GATTTCTCTYCCTGTTCTTGCA [GATTTCTCTCCCTGTTCTTGCA, GATTTCTCTTCCTGTTCTTGCA]

Why this dictionary values are all the same?

I am trying to write this dictionary comprehension and I don't know why all the dictionary values are the same.
The code is:
from string import ascii_uppercase
dictionary = {key: value for key in range(0, len(ascii_uppercase)) for value in ascii_uppercase}
The result is:
{0: 'Z', 1: 'Z', 2: 'Z', 3: 'Z', 4: 'Z', 5: 'Z', 6: 'Z', 7: 'Z', 8: 'Z', 9: 'Z', 10: 'Z', 11: 'Z', 12: 'Z', 13: 'Z', 14: 'Z', 15: 'Z', 16: 'Z', 17: 'Z', 18: 'Z', 19: 'Z', 20: 'Z', 21: 'Z', 22: 'Z', 23: 'Z', 24: 'Z', 25: 'Z'}
Why it is only giving me the last character of the string as all the values?
How can I fix it?
If you convert the dict comprehension into regular loops, you have this:
dictionary = {}
for key in range(0, len(ascii_uppercase)): # for every number in range 0-26
for value in ascii_uppercase: # for every letter in range a-z
dictionary[key] = value # d[num] = letter
The last letter for every number is 'z' so your dictionary is updated with it at the end of inner loop for each number.
You can try:
di = {}
for i, letter in enumerate(ascii_uppercase):
di[i] = letter
or
di = {i: letter for i, letter in enumerate(ascii_uppercase)}
or
di = dict(enumerate(ascii_uppercase))
Because the inner loop always end as the end of list, better is to Use enumerate() with dict() for this:
dictionary = dict(enumerate(ascii_uppercase))
The second for-loop gets fully executed before the first one so it messes up the result. You can try this approach with just one for-loop instead:
dictionary = {i: ascii_uppercase[i] for i in range(len(ascii_uppercase))}
Change your code to this
from string import ascii_uppercase
dictionary = {key: value for key,value in enumerate(ascii_uppercase, 0)}
Output
{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J', 10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O', 15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z'}
While there are other suitable answers, I believe this is what you think you are doing.
from string import ascii_uppercase
{key: value for key,value in zip(range(0, len(ascii_uppercase)),ascii_uppercase)}

Python. How to modify/replace elements of a list which is a value in a dictionary?

I have two dictionaries:
D_1 = {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14: 'N', 15: 'O', 16: 'P', 17: 'Q', 18: 'R', 19: 'S', 20: 'T', 21: 'U', 22: 'V', 23: 'W', 24: 'X', 25: 'Y', 26: 'Z'}
D_2 = {1: ['A', 'A', 'R', 'O', 'N'], 2: ['A', 'B', 'B', 'E', 'Y'], 3: ['A', 'B', 'B', 'I', 'E']}
My task is to replace the letters in values of D2 with corresponding keys from D1. For example I would want the first key and value pair in D2 to look like this : {1:[1,1,19,16,15]}
I have modified D2 where i made the values into lists instead of strings thinking that it would make my task easier.
dd = {v:k for (k, v) in D_1.items()}
{x: [dd[a] for a in y] for (x, y) in D_2.items()}
First line reverts D_1. Second line applies dd to values in D_2.
I think your D_1 is redundant. What you can do here is to use ascii_uppercase:
from string import ascii_uppercase
{k: [ascii_uppercase.index(i) + 1 for i in v] for k, v in D_2.items()}
Output:
{1: [1, 1, 18, 15, 14], 2: [1, 2, 2, 5, 25], 3: [1, 2, 2, 9, 5]}
Using ord
D_2 = {1: ['A', 'A', 'R', 'O', 'N'], 2: ['A', 'B', 'B', 'E', 'Y'], 3: ['A', 'B', 'B', 'I', 'E']}
{k: [ord(val)-64 for val in v] for (k, v) in D_2.items()}
Output:
{1: [1, 1, 18, 15, 14], 2: [1, 2, 2, 5, 25], 3: [1, 2, 2, 9, 5]}
m = map(lambda v:[{v: k for k, v in D_1.items()}[e] for e in v], D_2.values())
encapsulated in a map and create the new dictionary when useful:
dict(list(enumerate(m, start=1)))
# {1: [1, 1, 18, 15, 14], 2: [1, 2, 2, 5, 25], 3: [1, 2, 2, 9, 5]}

super simple cipher function in python. comparing a list to keys in a dictionary

I am working on ways to get me thinking in python. I have a simple idea that will take a number and give the corresponding "value" from a dictionary.
So basically I would like to have a number or numbers given, and then turn those numbers into a word.
The overall all view is to have a dictionary with keys ranging for 1 to 26 with values going from a to z. So 1 would equal "a" and 26 would equal "z".
I have a variable d = 1, and need to get the output of 'a'. Then increase size of this function for a list like (1,2,3,4) which output would be a, b, c, d.
Here is what I have so far.
d = 1
def code_scram(x):
c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
scram = ""
for i in d:
if i in c:
scram += c[i]
return scram
print code_scram(d)
However, its not working out as planned.
Your for loop should iterate through x, not d.
def code_scram(x):
c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
scram = ""
for i in x:
if i in c:
scram += c[i]
return scram
print code_scram([1,2,3,4])
Result:
abcd
The function only works for lists, so passing in the integer d won't work. Pass in a list instead.
d = [1]
print code_scram(d)
If you want the function to work for lists and lone integers, you can perform a type check, and convert as necessary.
def code_scram(x):
if isinstance(x, int):
x = [x]
c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
scram = ""
for i in x:
if i in c:
scram += c[i]
return scram
d = 1
print code_scram(d)
Result:
a

Categories

Resources