Related
This is what I have so far:
newlines = []
diction = {}
i = 0
w = 0
f = open('file1.txt')
lines = f.readlines()
while i <= len(lines)-1:
newlines.append(lines[i].strip('\n'))
i += 1
season= newlines[::2]
shows = newlines[1::2]
temp_list = []
while w <= len(season)-1 and w <= len(shows)-1:
diction[season[w]] = shows[w]
if '20' in diction:
temp_list.append(shows[w])
diction['20'] = temp_list
w += 1
print(diction)
Outcome
{'20': ['Gunsmoke', 'The Simpsons', 'Will & Grace', 'Dallas', 'Law & Order', 'Murder, She Wrote'], '30': 'The Simpsons', '10': 'Will & Grace', '14': 'Dallas', '12': 'Murder, She Wrote'}
Desired Outcome
{'20': 'Gunsmoke', 'Law & Order', '30': 'The Simpsons', '10': 'Will & Grade', '14': 'Dallas', '12' : 'Murder, She Wrote'}
What file1.txt contains
20
Gunsmoke
30
The Simpsons
10
Will & Grace
14
Dallas
20
Law & Order
12
Murder, She Wrote
I explained with comments.
f = open('text1.txt')
# Firstly read the text file with splitlines to not struggle with \n
lines = f.read().splitlines()
diction = {}
print(lines)
# Iterate each line
# lines = ['20 Gunsmoke', '30 The Simpsons', '10 Will & Grace', '14 Dallas', '20 Law & Order', '12 Murder, She Wrote']
for line in lines:
# We are splitting the line to take season count and series name
# It split with white space so we should merge the series name after taking the season count
# ex. splitted_line = ['30', 'The', 'Simpsons']
splitted_line = line.split()
# ex. season_count = '20'
season_count = splitted_line[0]
# ex. series_name = 'The' + ' ' + 'Simpsons'
series_name = ' '.join(splitted_line[1:])
# We can check whether the key we have exist in dictionar or not
if season_count in diction:
# If we have the key in dictionary
# First we should check it is a just string or array of string
# ex. It can be {'20': 'Gunsmoke'}
# We we can came with another series with same season count we should make it array
# ex. {'20': ['Gunsmoke', 'Law & Order'] }
# If we have already an array, we can just append it
temp = diction[season_count]
diction[season_count] = [temp, series_name] if isinstance(temp, str) else temp + [series_name]
else:
# If we have not key in dictionary we should add it to dictionary
diction[season_count] = series_name
print(diction)
You can use default dict from the collections library
from collections import defaultdict
data = """20 Gunsmoke
30 The Simpsons
10 Will & Grace
14 Dallas
20 Law & Order
12 Murder, She Wrote"""
data_dict = defaultdict(list)
for d in data.splitlines():
split = d.index(" ")
show = d[split+1:]
season = d[:split]
data_dict[season].append(show)
print(data_dict)
OUTPUT
defaultdict(<class 'list'>, {'20': ['Gunsmoke ', 'Law & Order'], '30': ['The Simpsons '], '10': ['Will & Grace '], '14': ['Dallas'], '12': ['Murder, She Wrote']})
Tried to do it while changing as little code as possible. To start with initialised a list for each key and then simply appended them using your for-loop. That way you don't have to hardcode checking for '20' existing
newlines = []
diction = {}
i = 0
w = 0
f = open('file.txt')
lines = f.readlines()
while i <= len(lines)-1:
newlines.append(lines[i].strip('\n'))
i += 1
print(newlines)
season = newlines[::2]
shows = newlines[1::2]
temp_list = []
for s in season:
diction[s] = []
while w <= len(season)-1 and w <= len(shows)-1:
diction[season[w]].append(shows[w])
w += 1
print(diction)
Outcome is the following (Uses lists for each key) :
{'20': ['Gunsmoke', 'Law & Order'], '30': ['The Simpsons'], '10': ['Will & Grace'], '14': ['Dallas'], '12': ['Murder, She Wrote']}
I've a list like this in python:
['name: "Ship_Date"',
'type: STRING',
'num_non_missing: 100000',
'name: "Units_Sold"',
'type: FLOAT',
'num_non_missing: 100000',
'tot_num_values: 100000',
'name: "Order_Date"'
'type: FLOAT',
'num_non_missing: 100000',
'name: "Region"',
'type: STRING',
'num_non_missing: 100000',
'tot_num_values: 100000',
'name: "Item_Type"',
'type: STRING',
'num_non_missing: 100000',
'tot_num_values: 100000']
Now I want to split this list at the point where 'name:' is present.
I want output like below:
[['name: "Ship_Date"',
'type: STRING',
'num_non_missing: 100000'],
['name: "Units_Sold"',
'type: FLOAT',
'num_non_missing: 100000',
'tot_num_values: 100000'],
['name: "Order_Date"'
'type: FLOAT',
'num_non_missing: 100000'],
['name: "Region"',
'type: STRING',
'num_non_missing: 100000',
'tot_num_values: 100000'],
['name: "Item_Type"',
'type: STRING',
'num_non_missing: 100000',
'tot_num_values: 100000']]
Please let me know if the problem is not clear enough. Thanks in advance.
Try this:
start = 0
new_lst = []
for i,elem in enumerate(x):
if elem.startswith('name'):
end = i
sublst = x[start:end]
if sublst:
new_lst.append(sublst)
start = i
new_lst.append(x[start:])
Output:
[['name: "Ship_Date"', 'type: STRING', 'num_non_missing: 100000'],
['name: "Units_Sold"',
'type: FLOAT',
'num_non_missing: 100000',
'tot_num_values: 100000'],
['name: "Order_Date"type: FLOAT', 'num_non_missing: 100000'],
['name: "Region"',
'type: STRING',
'num_non_missing: 100000',
'tot_num_values: 100000'],
['name: "Item_Type"',
'type: STRING',
'num_non_missing: 100000',
'tot_num_values: 100000']]
This also worked for me.
from itertools import groupby
li = ['abc',1,2,3,'abc',5,6,7,8,9000,10,11,12,1300]
class GroupbyHelper(object):
def __init__(self, val):
self.val = val
self.i = 0
def __call__(self, val):
self.i += (val == self.val)
return self.i
list2 = [list(g) for k, g in groupby(li, key=GroupbyHelper('abc'))]
print(list2)
I have made a morse code translator where you can put in a letter to print out the corresponding code and vice versa. However, the program is only limited for accepting one letter at a time. How can I make it accept a word? Here's my code:
MorseCode = {'.-':'A',
'-...':'B',
'-.-.':'C',
'-..':'D',
'.':'E',
'..-.':'F',
'--.':'G',
'....':'H',
'..':'I',
'.---':'J',
'-.-':'K',
'.-..':'L',
'--':'M',
'-.':'N',
'---':'O',
'.--.':'P',
'--.-':'Q',
'.-.':'R',
'...':'S',
'-':'T',
'..-':'U',
'...-':'V',
'.--':'W',
'-..-':'X',
'-.--':'Y',
'--..':'Z',
'.----':1,
'..---':2,
'...--':3,
'....-':4,
'.....':5,
'-....':6,
'--...':7,
'---..':8,
'----.':9,
'-----':0
}
letters_to_morse = {letter: code for code, letter in MorseCode.items()}
print "Type 'help' for the morse code."
print "Type 'end' to exit the program.\n"
while True:
code = raw_input("Enter code:")
if code in MorseCode:
print MorseCode[code]
elif code in letters_to_morse:
print letters_to_morse[code]
The question is: Is there a way to put in a word and splits that word to each letter so each letter would become a key to the dictionary to print out the value?
Example: the word 'boy' would be split into 'b','o','y' and then the program would print out: -... --- -.--
What I tried so far:
MorseCode = {'.-':'A',
'-...':'B',
'-.-.':'C',
'-..':'D',
'.':'E',
'..-.':'F',
'--.':'G',
'....':'H',
'..':'I',
'.---':'J',
'-.-':'K',
'.-..':'L',
'--':'M',
'-.':'N',
'---':'O',
'.--.':'P',
'--.-':'Q',
'.-.':'R',
'...':'S',
'-':'T',
'..-':'U',
'...-':'V',
'.--':'W',
'-..-':'X',
'-.--':'Y',
'--..':'Z',
'.----':1,
'..---':2,
'...--':3,
'....-':4,
'.....':5,
'-....':6,
'--...':7,
'---..':8,
'----.':9,
'-----':0
}
Inverse_Dictionary = {v:k for k,v in Dictionary.iteritems()}
while True:
x = raw_input("Enter:")
for letter in list(x):
if letter in Dictionary:
print (Dictionary[letter])
elif letter in Inverse_Dictionary:
print(Inverse_Dictionary[letter])
else:
print("Not good")
It worked. When I typed 'BOY' it printed out: -... --- -.-- but when I tried to enter -... --- -.--, it keeps printing out "Not good."
anyone can tell me where I went wrong?
Change
for letter in list(x):
To
for letter in x.split():
Also you got Inverse_Dictionary = {v:k for k,v in Dictionary.iteritems()}, however Dictionary is undefined, it should be Inverse_Dictionary = {v:k for k,v in MorseCode.iteritems()}
list(x) returns a list with character typed . So
list(' -... --- -.--,')
will return
[' ', '-', '.', '.', '.', ' ', '-', '-', '-', ' ', '-', '.', '-', '-', ',']
You need a way to diversify your input. For example leave a space between each letter/Morse code and then do:
while True:
x = raw_input("Enter:")
for letter in x.split(' '):
if letter in Dictionary:
print (Dictionary[letter])
elif letter in Inverse_Dictionary:
print(Inverse_Dictionary[letter])
else:
print("Not good")
I would try something like:
letters_to_morse = {letter: code for code, letter in MorseCode.items()}
string_to_convert = raw_input('Enter message you want to translate to morse...')
trans = ''
for char in string_to_convert:
if char.isdigit():
trans = trans + letters_to_morse[int(char)]
elif char == ' ':
trans = trans + ' '
else:
trans = trans + letters_to_morse[str.upper(char)]
print trans
This code does the trick pythonically:
morse.py
>>> def translate(word):
... inverse_morse = dict({str(v): k for k, v in MorseCode.items()},**{" ":" "})
... return "".join([inverse_morse[letter.upper()] for letter in word])
>>> print(translate("boy 123"))
-...----.-- .----..---...--
I have a problem with dictionaries that I need help with.
Here is an excerpt from weather.txt:
Hail : 1 : xxx
Hail : 2 : xxx
Hail : 3 : xxx
Rain : 1 : xxx
Rain : 2 : xxx
Rain : 3 : xxx
The first value is the weather, the second value is the intensity and the third is just a short description.
Here is an excerpt from my game:
weather = open("weather.txt")
weather_list = {}
for line in weather:
line = line.rstrip().split(":")
weather_list[line[0][int(line[1]) -1]] = (line[0], line[1], line[2])
for key, value in weather_list.items():
print key, ":", value
That prints this:
a : ('Rain ', ' 2 ', ' xxx')
i : ('Rain ', ' 3 ', ' xxx')
H : ('Hail ', ' 1 ', ' xxx')
R : ('Rain ', ' 1 ', ' xxx')
But I want it to print this:
'Rain': [('Rain ', ' 1 ', ' xxx'), ('Rain ', ' 2 ', ' xxx'), i : ('Rain ', ' 3 ', ' xxx')]
'Hail': etc...
I know my issue is with the syntax "weather_list[line[0][int(line[1]) -1]]". What I want it to do is have 1 key for each weather, and each value to be a tuple or list containing all the values for that weather, sorted by intensity, (intensity 1, intensity 2, intensity 3).
Any and all help is appreciated. Hope I explained it better this time.
Solution
This works:
weather = {}
with open('weather.txt') as fobj:
for line in fobj:
data = line.strip().split(':')
weather.setdefault(data[0], []).append(tuple(data))
weather = {key: sorted(value, key=lambda x: x[1]) for key, value in weather.items()}
The result looks like this:
>>> weather
{'Hail ': [('Hail ', ' 1 ', ' xxx'),
('Hail ', ' 2 ', ' xxx'),
('Hail ', ' 3 ', ' xxx')],
'Rain ': [('Rain ', ' 1 ', ' xxx'),
('Rain ', ' 2 ', ' xxx'),
('Rain ', ' 3 ', ' xxx')]}
Variation
The above solution has, as requested, redundant information for Rain and Hail. This version does not store them as first element in tuple but only as key in the dictionary:
weather = {}
with open('weather.txt') as fobj:
for line in fobj:
data = line.strip().split(':')
weather.setdefault(data[0], []).append(tuple(data[1:]))
weather = {key: sorted(value) for key, value in weather.items()}
The sorting is simpler and the result looks like this:
>>> weather
{'Hail ': [(' 1 ', ' xxx'), (' 2 ', ' xxx'), (' 3 ', ' xxx')],
'Rain ': [(' 1 ', ' xxx'), (' 2 ', ' xxx'), (' 3 ', ' xxx')]}
Hi i have the following code. When i run getDetails function the try:
does work but the exception is not displaying properly.
data_dict = {}
dict_list = []
def createNameDict(filename):
path = "C:\Users\user\Desktop"
basename = "ParkingData_Part2.txt"
filename = path + "//" + basename
file = open(filename)
contents = file.read()
print contents,"\n"
data_list = [lines.split(",") for lines in contents.split("\n")]
for line in data_list:
regNumber = line[0]
details = (line[1],line[2],line[3])
data_dict[regNumber] = details
print data_dict,"\n"
print data_dict.items(),"\n"
def getDetails(regNumber):
#if regNumber in data_dict:
try:
if regNumber in data_dict:
print data_dict[regNumber]
#print data_dict.get(regNumber)
except:
printNow(regNumber, "not in dictionary")
return
def addRegistration(regNumber, details):
try:
data_dict[regNumber] = details
except:
print regNumber, "Key Already exist"
#data_dict.update({regNumber:(details)})
return data_dict
The output I have is:
======= Loading Progam =======
>>> createNameDict("C:\Users\user\Desktop//ParkingData_Part2.txt")
EDF768, Bill Meyer, 2456, Vet_Parking
TY5678, Jane Miller, 8987, AgHort_Parking
GEF123, Jill Black, 3456, Creche_Parking
ABC234, Fred Greenside, 2345, AgHort_Parking
GH7682, Clara Hill, 7689, AgHort_Parking
JU9807, Jacky Blair, 7867, Vet_Parking
KLOI98, Martha Miller, 4563, Vet_Parking
ADF645, Cloe Freckle, 6789, Vet_Parking
DF7800, Jacko Frizzle, 4532, Creche_Parking
WER546, Olga Grey, 9898, Creche_Parking
HUY768, Wilbur Matty, 8912, Creche_Parking
{'HUY768': (' Wilbur Matty', ' 8912', ' Creche_Parking'), 'GH7682': (' Clara Hill', ' 7689', ' AgHort_Parking'), 'GEF123': (' Jill Black', ' 3456', ' Creche_Parking'), 'WER546': (' Olga Grey', ' 9898', ' Creche_Parking'), 'TY5678': (' Jane Miller', ' 8987', ' AgHort_Parking'), 'ABC234': (' Fred Greenside', ' 2345', ' AgHort_Parking'), 'KLOI98': (' Martha Miller', ' 4563', ' Vet_Parking'), 'EDF768': (' Bill Meyer', ' 2456', ' Vet_Parking'), 'JU9807': (' Jacky Blair', ' 7867', ' Vet_Parking'), 'DF7800': (' Jacko Frizzle', ' 4532', ' Creche_Parking'), 'ADF645': (' Cloe Freckle', ' 6789', ' Vet_Parking')}
[('HUY768', (' Wilbur Matty', ' 8912', ' Creche_Parking')), ('GH7682', (' Clara Hill', ' 7689', ' AgHort_Parking')), ('GEF123', (' Jill Black', ' 3456', ' Creche_Parking')), ('WER546', (' Olga Grey', ' 9898', ' Creche_Parking')), ('TY5678', (' Jane Miller', ' 8987', ' AgHort_Parking')), ('ABC234', (' Fred Greenside', ' 2345', ' AgHort_Parking')), ('KLOI98', (' Martha Miller', ' 4563', ' Vet_Parking')), ('EDF768', (' Bill Meyer', ' 2456', ' Vet_Parking')), ('JU9807', (' Jacky Blair', ' 7867', ' Vet_Parking')), ('DF7800', (' Jacko Frizzle', ' 4532', ' Creche_Parking')), ('ADF645', (' Cloe Freckle', ' 6789', ' Vet_Parking'))]
>>> getDetails("GFT245")
>>> getDetails("HUY768")
(' Wilbur Matty', ' 8912', ' Creche_Parking')
>>> getDetails("JU9807")
(' Jacky Blair', ' 7867', ' Vet_Parking')
>>> getDetails("GH7682")
(' Clara Hill', ' 7689', ' AgHort_Parking')
>>>
If GFT245 is not in dictionary it should show
GFT245 not in dictionary
but its not coming that way when i execute the program
The problem is located here:
if regNumber in data_dict:
print data_dict[regNumber]
As you are asking whether regNumber is or is not present in the dictionary the exception will never be raised due to the fact that in case regNumber is not present you will not try to index it, thus not raising the KeyError exception.
If you want the exception to be raised then just do:
print data_dict[regNumber]
In your getDetails function the except section will never fire as you explicitly check if the key is in the dictionary before you access it, you would want to re-write it either as
if key in dict:
# The key exists and do something
else:
# The key doesn't exist, notify the user
or
try:
print dict[key]
except KeyError:
# The key doesn't exist, notify the user
I prefer the style of the first as exceptions are expensive, of course if you know that you will only have a small number of keys that do not exist in the dictionary and would cause the exception, then you could optimize the second way.
And your addRegistration function should be re-written to test if the key exists already and notify the user, else add the data, as it will not warn you or raise an exception if the key already exists, it will just update/replace the data for that key.
if regNumber in data_dict:
print data_dict[regNumber]
You have a conditional before accessing data_dict. If regNumber is not in dict then it will not try to access it. Hence no exception is thrown.
def getDetails(regNumber):
#if regNumber in data_dict:
try:
if regNumber in data_dict:
print data_dict[regNumber]
#print data_dict.get(regNumber)
except:
printNow(regNumber, "not in dictionary")
return
Nothing in that try block is actually failing.
Why? Because of the if regNumber in data_dict test. If the code is not in the dictionary, it will never attempt to look it up.
Perhaps you meant something like:
def getDetails(regNumber):
if regNumber in data_dict:
print data_dict[regNumber]
else:
printNow(regNumber, "not in dictionary")
The problem is
try:
if regNumber in data_dict:
print data_dict[regNumber]
#print data_dict.get(regNumber)
except:
printNow(regNumber, "not in dictionary")
if regNumber is not in data_dict, no exception occures. Change it to:
try:
print data_dict[regNumber]
except:
printNow(regNumber, "not in dictionary")