I need to match two lists one with characters and other with words
My current code is:
char_list=['G','UH','D','S', 'ER', 'M', 'AY', 'S', 'EH', 'L', 'F', 'B', 'AE', 'NG', 'K']
word_list=['GUHD','MAORNIHNG','SER','MAY','SEHLF','BAENGK']
for word_p in word_list:
scores = {}
p_s=""
if str(word_p) != "NULL":
print(word_p)
for j in char_list:
if len(word_p) == len(p_s):
print("word end")
for i in scores.keys():
char_list.remove(i)
break
else:
if j in word_p:
p_s=p_s+j
scores[j] = gop_scores.get(str(j))#this returns an integer value corresponding to char
sep_scores[str(word_p)] = scores
print(sep_scores)
The current output is:-
*{'GUHD': {'G': 100.0, 'UH': 18.142809657631524, 'D': 61.62375099467158}, 'MAORNIHNG': {'M': 100.0, 'NG': 43.40719714138942}, 'SER': {'S': 100.0, 'ER': 100.0}, 'MAY': {'M': 100.0, 'AY': 100.0}, 'SEHLF': {'S': 100.0, 'EH': 89.72295878282416, 'L': 100.0, 'F': 0.0}, 'BAENGK': {'B': 7.166608749080874, 'AE': 68.10287800038276, 'NG': 43.40719714138942, 'K': 100.0}}}*
Note
Everything seems fine but there is no exact matching char for MAORNIHNG and still i am getting{'M','NG'}, I want the MAORNIHNG value to be empty
expected output
*{'GUHD': {'G': 100.0, 'UH': 18.142809657631524, 'D': 61.62375099467158}, 'MAORNIHNG': {}, 'SER': {'S': 100.0, 'ER': 100.0}, 'MAY': {'M': 100.0, 'AY': 100.0}, 'SEHLF': {'S': 100.0, 'EH': 89.72295878282416, 'L': 100.0, 'F': 0.0}, 'BAENGK': {'B': 7.166608749080874, 'AE': 68.10287800038276, 'NG': 43.40719714138942, 'K': 100.0}}}*
The 'MAORNIHNG' value should be empty dict
You just need to make sure that the dictionary keys form the entire word, and if not return an empty dict, you can do this by joining them and comparing:
char_list=['G','UH','D','S', 'ER', 'M', 'AY', 'S', 'EH', 'L', 'F', 'B', 'AE', 'NG', 'K']
word_list=['GUHD','MAORNIHNG','SER','MAY','SEHLF','BAENGK']
sep_scores={}
for word_p in word_list:
scores = {}
p_s=""
if str(word_p) != "NULL":
print(word_p)
for j in char_list:
if len(word_p) == len(p_s):
print("word end")
for i in scores.keys():
char_list.remove(i)
break
else:
if j in word_p:
p_s=p_s+j
scores[j] = 1#this returns an integer value corresponding to char
if ''.join(scores.keys()) == word_p:
sep_scores[str(word_p)] = scores
else:
sep_scores[str(word_p)] = {}
print(sep_scores)
>>> {'GUHD': {'G': 1, 'UH': 1, 'D': 1}, 'MAORNIHNG': {}, 'SER': {'S': 1, 'ER': 1}, 'MAY': {'M': 1, 'AY': 1}, 'SEHLF': {'S': 1, 'EH': 1, 'L': 1, 'F': 1}, 'BAENGK': {'B': 1, 'AE': 1, 'NG': 1, 'K': 1}}
Related
Here we go again. One 'fairly easy' exercise that has finally given me headache.
Make a program that uses a lookup table to convert any set of alphabets into their corresponding NATO phonetic alphabets (https://en.wikipedia.org/wiki/NATO_phonetic_alphabet). Also implement the inverse function.
Input: cat
Output: charlie alfa tango
Inverse function:
Input : charlie alfa tango
Output : cat
I have defined a dictionary with the alphabet and its Nato equivalent for each letter. Then, I have defined a function that will take elements from a list as input. Letter corresponds to my keys in the dictionary and letter conversion corresponds to my values. The function works in the following cases:
When I enter a single character, it will give me its 'Nato' equivalent. (comparing the string with letter and outputting the letter conversion)
When I enter a string that is Nato alphabet it will output the letter. (comparing the string with the letter conversion and outputting the letter)
I'm getting stuck when I need to evaluate the lenght of the string from my list, and then
convert each character into its Nato alphabet.
nato_alphabet = {'a':'Alfa', 'A': 'Alfa', 'b': 'Bravo', 'B': 'Bravo', 'c': 'Charlie', 'C': 'Charlie', 'd': 'Delta', 'D':'Delta', 'e': 'Echo', 'E':'Echo', 'f': 'Foxtrot', 'F': 'Foxtrot', 'G': 'Golf', 'g': 'Golf', 'h': 'Hotel', 'H': 'Hotel', 'k': 'Kilo', 'K': 'Kilo', 'l': 'Lima', 'L': 'Lima', 'm': 'Mike', 'M': 'Mike', 'n': 'November', 'N': 'November', 'o': 'Oscar', 'O': 'Oscar',
'p': 'Papa', 'P': 'Papa', 'q': 'Quebec', 'Q': 'Quebec', 'r': 'Romeo', 'R': 'Romeo', 's': 'Sierra', 'S': 'Sierra', 't':'Tango', 'T': 'Tango', 'u': 'Uniform', 'U': 'Uniform', 'V': 'Victor', 'v': 'Victor', 'w': 'Whiskey', 'W': 'Whiskey', 'y': 'Yankee', 'Y': 'Yankee', 'Z': 'Zulu', 'z': 'Zulu'}
#Passing through a list
def convert(word_to_convert):
word_converted= []
for i in word_to_convert:
for letter, letter_conversion in nato_alphabet.items():
if i == letter:
word_converted.append(letter_conversion)
if i == letter_conversion:
word_converted.append(letter)
if len(i) == letter:
word_converted.append(letter_conversion )
return word_converted
print(convert(['c', 'Alfa', 'moon']))
Thank you everyone for your help !
Diana
Use:
def convert(word_to_convert):
word_converted = []
for i in word_to_convert:
word_converted.append(" ".join(nato_alphabet[ii.lower()] for ii in i))
return word_converted
print(convert(['c', 'Alfa', 'moon']))
Output
['Charlie', 'Alfa Lima Foxtrot Alfa', 'Mike Oscar Oscar November']
As an alternative:
# Passing through a list
def convert(words_to_convert):
word_converted = []
# iterate over each word
for word in words_to_convert:
nato_encoded_list = []
# iterate over each character in word
for char in word:
# fetch the corresponding value from nato_alphabet
nato_encoded_list.append(nato_alphabet[char.lower()])
# join the encoded words and add to word_converted list
word_converted.append(" ".join(nato_encoded_list))
return word_converted
Basically iterate over each, word and for each character in the word fetch the nato_alphabet value.
This might let me know if something is unclear
nato_alphabet = {'a':'Alfa', 'A': 'Alfa', 'b': 'Bravo', 'B': 'Bravo', 'c': 'Charlie', 'C': 'Charlie', 'd': 'Delta', 'D':'Delta', 'e': 'Echo', 'E':'Echo', 'f': 'Foxtrot', 'F': 'Foxtrot', 'G': 'Golf', 'g': 'Golf', 'h': 'Hotel', 'H': 'Hotel', 'k': 'Kilo', 'K': 'Kilo', 'l': 'Lima', 'L': 'Lima', 'm': 'Mike', 'M': 'Mike', 'n': 'November', 'N': 'November', 'o': 'Oscar', 'O': 'Oscar',
'p': 'Papa', 'P': 'Papa', 'q': 'Quebec', 'Q': 'Quebec', 'r': 'Romeo', 'R': 'Romeo', 's': 'Sierra', 'S': 'Sierra', 't':'Tango', 'T': 'Tango', 'u': 'Uniform', 'U': 'Uniform', 'V': 'Victor', 'v': 'Victor', 'w': 'Whiskey', 'W': 'Whiskey', 'y': 'Yankee', 'Y': 'Yankee', 'Z': 'Zulu', 'z': 'Zulu'}
nato_alphabet_inverse = {v.lower():k.lower() for k,v in nato_alphabet.items()}
nato_alphabet = {k.lower():v.lower() for k,v in nato_alphabet.items()}
# print(nato_alphabet_inverse)
def convert(list_to_convert):
return_list = []
for each_item in list_to_convert:
# print(each_item)
if " " in each_item: # Sentence thus must be converted to Alphabets
l_ = each_item.split()
temp_list = []
for each_word in l_:
# print(each_word)
temp_list.append(nato_alphabet_inverse[each_word.lower()])
# return_list.append()
return_list.append("".join(temp_list))
else: # Convert to equivalent Nato
temp_list = []
for chr in each_item:
# print(chr)
temp_list.append(nato_alphabet[chr.lower()])
str_ = " ".join(temp_list)
return_list.append(str_)
return return_list
print(convert(['cAT',"charlie alfa tango"]))
I am trying to extract information from a list within a list within a list to end up with something like this from the information below: ('h': '0.77584', 'l': '0.77292'), ('h': '0.77521', 'l': '0.77206')
print(dict)
[{'complete': True, 'volume': 2290, 'time': '2021-01-15', 'mid': {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}}, {'complete': True, 'volume': 2312, 'time': '2021-01-15', 'mid': {'o': '0.77436', 'h': '0.77521', 'l': '0.77206', 'c': '0.77206'}}]
Not sure how to go about it. I tried
something = list(list(dict.items())[0].items())[3][1]
print(something)
However, this returned {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}
How to get the requested data?
You can use the following list and dict comprehension
dict = [{'complete': True, 'volume': 2290, 'time': '2021-01-15', 'mid': {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}}, {'complete': True, 'volume': 2312, 'time': '2021-01-15', 'mid': {'o': '0.77436', 'h': '0.77521', 'l': '0.77206', 'c': '0.77206'}}]
res = [{k:v for k, v in i['mid'].items() if k in 'hl'} for i in dict]
print(res)
Output
[{'h': '0.77584', 'l': '0.77292'}, {'h': '0.77521', 'l': '0.77206'}]
First you can take the mid child from each parent dictionary in the list.
dict = [{'complete': True, 'volume': 2290, 'time': '2021-01-15', 'mid': {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}}, {'complete': True, 'volume': 2312, 'time': '2021-01-15', 'mid': {'o': '0.77436', 'h': '0.77521', 'l': '0.77206', 'c': '0.77206'}}]
old_dict = [dict[0]['mid'],dict[1]['mid']]
Then loop through those entries and filter based off the keys (i.e. remove o and c):
list_you_want = []
for i in [0,1]:
list_you_want.append({ your_key: old_dict[i][your_key] for your_key in ['h','l'] })
Which gives you:
[{'h': '0.77584', 'l': '0.77292'}, {'h': '0.77521', 'l': '0.77206'}]
I'm trying to convert all values of some dictionaries that are nested in another dictionary.
I want to convert:
{0: {'n': 1}, 1: {'s': 0, 'n': 2}, 2: {'s': 1}}
To this:
{0: {'n': '?'}, 1: {'s': '?', 'n': '?'}, 2: {'s': '?'}}
I tried this:
for key, value in new_dictt:
new_dictt[key][value] = '?'
But it did not work. I've been googling but have not found a way to convert all values of all dictionaries within another dictionary.
Here we go:
old_dict = {0: {'n': 1}, 1: {'s': 0, 'n': 2}, 2: {'s': 1}}
new_dict = {key: {k: '?' for k in dct} for key, dct in old_dict.items()}
print(new_dict)
Which yields
{0: {'n': '?'}, 1: {'s': '?', 'n': '?'}, 2: {'s': '?'}}
This uses two nested dict comprehensions.
I have a list of tuples (variable name 'values') in the format
(1, 'K', '-', 0.8878048780487805)
(2, 'Y', '-', 0.32882882882882886)
(3, 'E', '-', 0.7216494845360825)
(4, 'Y', 'B', 0.13963963963963963)
(5, 'V', '-', 0.28169014084507044)
(6, 'E', '-', 0.39690721649484534)
.....
And I have this dictionary
ratios = {'K': 1.1512, 'A': 1.217, 'R': 1.1048, 'N': 1.242, 'D': 1.184,
'C': 1.237, 'Q': 1.1364, 'G': 1.2381, 'H': 1.2174, 'I': 1.1657,
'L': 1.1657, 'M': 1.1914, 'F': 1.2182, 'P': 1.1691, 'S': 1.1923,
'T': 1.2113, 'W': 1.2555, 'Y': 1.1847, 'V':1.2254}
What I would like to do is go through my list and divide the element in index 3 by the value in the dictionary that corresponds to the letter in index 1. For example, 0.8878... would be divided by 1.1512 because of the K, for the next one 0.3288.... would be divided by 1.1847 because of the Y, and so on. I haven't found a way to do this yet.
A list comprehension should work great here
tuple_list =[(1, 'K', '-', 0.8878048780487805),
(2, 'Y', '-', 0.32882882882882886),
(3, 'E', '-', 0.7216494845360825),
(4, 'Y', 'B', 0.13963963963963963),
(5, 'V', '-', 0.28169014084507044),
(6, 'E', '-', 0.39690721649484534)]
ratios = {'K': 1.1512, 'A': 1.217, 'R': 1.1048, 'N': 1.242, 'D': 1.184,
'C': 1.237, 'Q': 1.1364, 'G': 1.2381, 'H': 1.2174, 'I': 1.1657,
'L': 1.1657, 'M': 1.1914, 'F': 1.2182, 'P': 1.1691, 'S': 1.1923,
'T': 1.2113, 'W': 1.2555, 'Y': 1.1847, 'V':1.2254}
[tup[3]/ratios.get(tup[1],1) for tup in tuple_list]
use get so it will not throw an error if key is not present in ratios
Output
[0.7711995118561331,
0.2775629516576592,
0.7216494845360825,
0.11786919864914291,
0.22987607380860978,
0.39690721649484534]
for row in values:
print(row[1], row[3]/ratios[row[1]])
my_tuple_list = [
(1, 'K', '-', 0.8878048780487805),
.....
]
result = {}
for (idx, key, _, number) in my_tuple_list:
result[key] = number / ratios[key]
print(result)
This solution shows how to unpack a list of tuples in a clear manner that may be easier to read than list comprehensions
For the following code, I'm trying to print out the values within a list of tuples that are mapped from the line to it based on column headers. However, the mapping seems to go awry and do not give me the values I want.
import itertools as it
def buc(column_headers, tuples):
row_dict = {}
attribs = [1,2]
measure = 10
# generate binary table based on number of columns
binaries = [i for i in it.product(range(2), repeat=(len(attribs)))]
for line in binaries:
line = list(line)
# replace binary of 1 with 'ALL' or 0 with value from input attribs
for index, item in enumerate(line):
if (item == 1):
line[index] = 'ALL'
elif (item == 0):
line[index] = attribs[index]
line.append(measure)
print(line)
# map column values to column heading by index and store in row_dict (e.g. {'A': 1, 'B': 'ALL', 'M': 100} )
for i in range(len(line)):
row_dict[column_headers[i]] = line[i]
tuples.append(row_dict)
print(tuples)
The following is the current output I get:
>>> buc(['A', 'B', 'M'], [])
[1, 2, 10]
[1, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
[{'A': 'ALL', 'B': 'ALL', 'M': 10}, {'A': 'ALL', 'B': 'ALL', 'M': 10}, {'A': 'ALL', 'B': 'ALL', 'M': 10}, {'A': 'ALL', 'B': 'ALL', 'M': 10}]
The correct output I want should be the following, where the lines is mapped to the tuples correctly, based on index of the column headings:
>>> buc(['A', 'B', 'M'], [])
[1, 2, 10]
[1, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
[{'A': '1', 'B': '2', 'M': 10}, {'A': '1', 'B': 'ALL', 'M': 10}, {'A': 'ALL', 'B': '2', 'M': 10}, {'A': 'ALL', 'B': 'ALL', 'M': 10}]
Where have I done wrong?
This happens because your list tuples only contains a reference to the original dictionary. See this answer. You can fix this by copying the dictionary.
Replace
tuples.append(row_dict)
with
tuples.append(row_dict.copy())