Re: Creating a Dictionary

2017-10-07 Thread Pavol Lisy
On 10/5/17, Chris Angelico  wrote:
> On Thu, Oct 5, 2017 at 12:24 PM, Stefan Ram  wrote:
>>   One might wish to implement a small language with these commands:
>>
>> F - move forward
>> B - move backward
>> L - larger stepsize
>> S - smaller stepsize
>>
>>   . One could start with the following pseudocode for a dictionary:
>>
>> { 'F': lambda: myturtle.forward( s ),
>>   'B': lambda: myturtle.backward( s ),
>>   'L': lambda: global s; s *= 2,
>>   'S': lambda: global s; s /= 2 }
>>
>>   . But lambda-expressions cannot contain statements.
>>
>>   Any other suggestions?
>
> There are a few options here. One is to make use of a simple
> "collector decorator":
>
> commands = {}
> def cmd(f):
> commands[f.__name__.upper()] = f
> return f
>
> @cmd
> def f():
> myturtle.forward( s )
>
> @cmd
> def b():
> myturtle.backward( s )
>
> @cmd
> def l():
> global siz
> size *= 2
>
> @cmd
> def s():
> global siz
> size //= 2
>
> (Also untested, but the pattern is one I've used many times.)
>
> Another is to deploy the whole thing as a class, with no globals:
>
> class Turtle:
> def __init__(self):
> self.size = ...
> self.turtle = ...
> def cmd_F(self):
> self.turtle.forward(self.size)
> def cmd_B(self):
> self.turtle.backward(self.size)
> def cmd_L(self):
> self.size *= 2
> def cmd_S(self):
> self.size //= 2
>
> Note that I've added "cmd_" in front of the names, which means you can
> safely getattr(turtle, "cmd_" + letter) and be confident you won't
> accidentally grab something that isn't a command.
>
> (Note also that I used // for division. If your size is actually a
> float, then change those back to single slashes.)
>
> Either of these patterns would work fairly well. There are others,
> too, but I'd be inclined to use one of these.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list

size = 2*size if size else 1
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a Dictionary

2017-10-04 Thread Chris Angelico
On Thu, Oct 5, 2017 at 12:24 PM, Stefan Ram  wrote:
>   One might wish to implement a small language with these commands:
>
> F - move forward
> B - move backward
> L - larger stepsize
> S - smaller stepsize
>
>   . One could start with the following pseudocode for a dictionary:
>
> { 'F': lambda: myturtle.forward( s ),
>   'B': lambda: myturtle.backward( s ),
>   'L': lambda: global s; s *= 2,
>   'S': lambda: global s; s /= 2 }
>
>   . But lambda-expressions cannot contain statements.
>
>   Any other suggestions?

There are a few options here. One is to make use of a simple
"collector decorator":

commands = {}
def cmd(f):
commands[f.__name__.upper()] = f
return f

@cmd
def f():
myturtle.forward( s )

@cmd
def b():
myturtle.backward( s )

@cmd
def l():
global siz
size *= 2

@cmd
def s():
global siz
size //= 2

(Also untested, but the pattern is one I've used many times.)

Another is to deploy the whole thing as a class, with no globals:

class Turtle:
def __init__(self):
self.size = ...
self.turtle = ...
def cmd_F(self):
self.turtle.forward(self.size)
def cmd_B(self):
self.turtle.backward(self.size)
def cmd_L(self):
self.size *= 2
def cmd_S(self):
self.size //= 2

Note that I've added "cmd_" in front of the names, which means you can
safely getattr(turtle, "cmd_" + letter) and be confident you won't
accidentally grab something that isn't a command.

(Note also that I used // for division. If your size is actually a
float, then change those back to single slashes.)

Either of these patterns would work fairly well. There are others,
too, but I'd be inclined to use one of these.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a Dictionary

2017-10-04 Thread Bill

Stefan Ram wrote:

   One might wish to implement a small language with these commands:

Explain why. What is the advantage?




F - move forward
B - move backward
L - larger stepsize
S - smaller stepsize

   . One could start with the following pseudocode for a dictionary:

{ 'F': lambda: myturtle.forward( s ),
   'B': lambda: myturtle.backward( s ),
   'L': lambda: global s; s *= 2,
   'S': lambda: global s; s /= 2 }

   . But lambda-expressions cannot contain statements.

   In real Python one could write something like (untested):

def f():
 myturtle.forward( s )

def b():
 myturtle.backward( s )

def l():
 global siz
 size *= 2

def s():
 global siz
 size /= 2

{ 'F': f,
   'B': b,
   'L': l,
   'S': s }

   . Is this more readable or less readable?

   Any other suggestions?



--
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-04-03 Thread Neil Cerutti
On 2013-04-01, Steven D'Aprano  wrote:
> On Mon, 01 Apr 2013 11:41:03 +, Neil Cerutti wrote:
>
>
>> I tried searching for Frost*, an interesting artist I recently learned
>> about. 
>
> "Interesting artist" -- is that another term for "wanker"?
>
> *wink*

hee-hee. It depends on how much of a hankering you have for
pretentious progressive synth-rock.

>> His name, in combination with a similarly named rap artist,
>> breaks most search tools.
>
> As far as I'm concerned, anyone in the 21st century who names
> themselves or their work (a movie, book, programming language,
> etc.) something which breaks search tools is just *begging* for
> obscurity, and we ought to respect their wishes.

I do think it's something he did on purpose. The asterisk, I
believe, symbolizes the exclusive genius of his fans.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-04-01 Thread Walter Hurry
On Mon, 01 Apr 2013 23:53:40 +, Steven D'Aprano wrote:

> As far as I'm concerned, anyone in the 21st century who names themselves
> or their work (a movie, book, programming language, etc.) something
> which breaks search tools is just *begging* for obscurity, and we ought
> to respect their wishes.

IIRC, there was an eccentric musician some years back who did just that.

I seem to remember that he changed his name to some kind of androgynous 
looking rune with what appeared to be a bent trumpet across it.

Thenceforth it became known as "the (piss) artist: formally gnome ass 
prints", or at least something sounding vaguely like that.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-04-01 Thread Dave Angel

On 04/01/2013 07:53 PM, C.T. wrote:

Thanks for all the help everyone! After I manually edited the txt file, this is 
what I came up with:

car_dict = {}
car_file = open('cars.txt', 'r')



for line in car_file:
 temp = line.strip().split(None, 2)
 temp2 = line.strip().split('\t')


 if len(temp)==3:
 year, manufacturer, model = temp[0] ,temp2[0][5:], temp2[1]
 value = (year, model)
 if manufacturer in car_dict:
 car_dict.setdefault(manufacturer,[]).append(value)


That's rather redundant.  Once you've determined that the particular key 
is already there, why bother with the setdefault() call?  Or to put it 
another way, why bother to test if it's there when you're going to use 
setdefault to handle the case where it's not?




 else:
 car_dict[manufacturer] = [value]


 elif len(temp)==2:
 year, manufacturer, model = temp[0], 'Unknown' , temp2[1]
 value = (year, model)
 if manufacturer in car_dict:
 car_dict.setdefault(manufacturer,[]).append(value)
 else:
 car_dict[manufacturer] = [value]


car_file.close()

print (car_dict)

It may not be the most pythonic way of doing this, but it works for me. I am 
learning python, and this problem was problem the most challenging so far. 
Thank you all, again!




--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-04-01 Thread C.T.
Thanks for all the help everyone! After I manually edited the txt file, this is 
what I came up with:

car_dict = {}
car_file = open('cars.txt', 'r')


 
for line in car_file: 
temp = line.strip().split(None, 2)
temp2 = line.strip().split('\t')


if len(temp)==3:  
year, manufacturer, model = temp[0] ,temp2[0][5:], temp2[1]
value = (year, model)
if manufacturer in car_dict:
car_dict.setdefault(manufacturer,[]).append(value)
else:
car_dict[manufacturer] = [value]


elif len(temp)==2:
year, manufacturer, model = temp[0], 'Unknown' , temp2[1]
value = (year, model)
if manufacturer in car_dict:
car_dict.setdefault(manufacturer,[]).append(value)
else:
car_dict[manufacturer] = [value]


car_file.close()

print (car_dict)

It may not be the most pythonic way of doing this, but it works for me. I am 
learning python, and this problem was problem the most challenging so far. 
Thank you all, again!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-04-01 Thread Steven D'Aprano
On Mon, 01 Apr 2013 11:41:03 +, Neil Cerutti wrote:


> I tried searching for Frost*, an interesting artist I recently learned
> about. 

"Interesting artist" -- is that another term for "wanker"?

*wink*


> His name, in combination with a similarly named rap artist,
> breaks most search tools.

As far as I'm concerned, anyone in the 21st century who names themselves 
or their work (a movie, book, programming language, etc.) something which 
breaks search tools is just *begging* for obscurity, and we ought to 
respect their wishes.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-04-01 Thread Neil Cerutti
On 2013-03-31, Roy Smith  wrote:
> And, this is a good excuse to explore some of the interesting
> third-party modules.  For example, mwclient ("pip install
> mwclient") gives you a neat Python interface to wikipedia.  And
> there's a whole landscape of string matching packages to
> explore.
>
> We deal with this every day at Songza.  Are Kesha and Ke$ha the
> same artist?  Pushing back on the record labels to clean up
> their catalogs isn't going to get us very far.

I tried searching for Frost*, an interesting artist I recently
learned about. His name, in combination with a similarly named
rap artist, breaks most search tools.

My guess is this homework is simply borken.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread Dave Angel

On 03/31/2013 02:41 PM, Roy Smith wrote:

In article ,
  Dave Angel  wrote:


On 03/31/2013 12:52 PM, C.T. wrote:

On Sunday, March 31, 2013 12:20:25 PM UTC-4, zipher wrote:

  



Thank you, Mark! My problem is the data isn't consistently ordered. I can
use slicing and indexing to put the year into a tuple, but because a car
manufacturer could have two names (ie, Aston Martin) or a car model could
have two names(ie, Iron Duke), its harder to use slicing and indexing for
those two.  I've added the following, but the output is still not what I
need it to be.


So the correct answer is "it cannot be done," and an explanation.

Many times I've been given impossible conditions for a problem.  And
invariably the correct solution is to press [back] on the supplier of the
constraints.


In real life, you often have to deal with crappy input data (and bogus
project requirements).  Sometimes you just need to be creative.

There's only a small set of car manufacturers.  A good start would be
mining wikipedia's [[List of automobile manufacturers]].  Once you've
got that list, you could try matching portions of the input against the
list.

Depending on how much effort you wanted to put into this, you could
explore all sorts of fuzzy matching (ie "delorean" vs "delorean motor
company"), but even a simple search is better than giving up.

And, this is a good excuse to explore some of the interesting
third-party modules.  For example, mwclient ("pip install mwclient")
gives you a neat Python interface to wikipedia.  And there's a whole
landscape of string matching packages to explore.

We deal with this every day at Songza.  Are Kesha and Ke$ha the same
artist?  Pushing back on the record labels to clean up their catalogs
isn't going to get us very far.



I agree with everything you've said, although in your case, presumably 
the record labels are not your client/boss, so that's not who you push 
back against.  The client should know when the data is being fudged, and 
have a say in how it's to be done.


But this is a homework assignment.  I think the OP is learning Python, 
not how to second-guess a client.



--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread Terry Jan Reedy

On 3/31/2013 11:52 AM, C.T. wrote:

Hello,

I'm currently working on a homework problem that requires me to create a 
dictionary from a .txt file that contains some of the worst cars ever made. The 
file looks something like this:

1958 MGA Twin Cam
1958 Zunndapp Janus
1961 Amphicar
1961 Corvair
1966 Peel Trident
1970 AMC Gremlin
1970 Triumph Stag
1971 Chrysler Imperial LeBaron Two-Door Hardtop

The car manufacturer should be the key and a tuple containing the year and the 
model should be the key's value. I tried the following to just get the contents 
of the file into a list, but only the very last line in the txt file is shown 
as a list with three elements (ie, ['2004', 'Chevy', 'SSR']) when I print temp.

d={}
car_file = open('worstcars.txt', 'r')
for line in car_file:
 temp = line.split()


If all makers are one word (Austen-Martin would be ok, and if the file 
is otherwise consistently year maker model words, then adding 
'maxsplit=3' to the split call would be all the parsing you need.




--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread Roy Smith
In article ,
 Dave Angel  wrote:

> On 03/31/2013 12:52 PM, C.T. wrote:
> > On Sunday, March 31, 2013 12:20:25 PM UTC-4, zipher wrote:
> >>  
> >>
> >
> > Thank you, Mark! My problem is the data isn't consistently ordered. I can 
> > use slicing and indexing to put the year into a tuple, but because a car 
> > manufacturer could have two names (ie, Aston Martin) or a car model could 
> > have two names(ie, Iron Duke), its harder to use slicing and indexing for 
> > those two.  I've added the following, but the output is still not what I 
> > need it to be.
> 
> So the correct answer is "it cannot be done," and an explanation.
> 
> Many times I've been given impossible conditions for a problem.  And 
> invariably the correct solution is to press [back] on the supplier of the 
> constraints.

In real life, you often have to deal with crappy input data (and bogus 
project requirements).  Sometimes you just need to be creative.

There's only a small set of car manufacturers.  A good start would be 
mining wikipedia's [[List of automobile manufacturers]].  Once you've 
got that list, you could try matching portions of the input against the 
list.

Depending on how much effort you wanted to put into this, you could 
explore all sorts of fuzzy matching (ie "delorean" vs "delorean motor 
company"), but even a simple search is better than giving up.

And, this is a good excuse to explore some of the interesting 
third-party modules.  For example, mwclient ("pip install mwclient") 
gives you a neat Python interface to wikipedia.  And there's a whole 
landscape of string matching packages to explore.

We deal with this every day at Songza.  Are Kesha and Ke$ha the same 
artist?  Pushing back on the record labels to clean up their catalogs 
isn't going to get us very far.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread Dave Angel

On 03/31/2013 12:52 PM, C.T. wrote:

On Sunday, March 31, 2013 12:20:25 PM UTC-4, zipher wrote:

 



Thank you, Mark! My problem is the data isn't consistently ordered. I can use 
slicing and indexing to put the year into a tuple, but because a car 
manufacturer could have two names (ie, Aston Martin) or a car model could have 
two names(ie, Iron Duke), its harder to use slicing and indexing for those two. 
 I've added the following, but the output is still not what I need it to be.




So the correct answer is "it cannot be done," and an explanation.

Many times I've been given impossible conditions for a problem.  And 
invariably the correct solution is to press bac on the supplier of the 
constraints.


Unless there are some invisible characters in that file, lie tabs in 
between the fields, it loocs liec you're out of luc.  Or you could 
manually edit the file before running the program.


[The character after 'j' is broccen on this cceyboard.]
--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread C.T.
On Sunday, March 31, 2013 12:38:56 PM UTC-4, Roy Smith wrote:
> In article ,
> 
>  "C.T."  wrote:
> 
> 
> 
> > Hello,
> 
> > 
> 
> > I'm currently working on a homework problem that requires me to create a 
> 
> > dictionary from a .txt file that contains some of the worst cars ever made. 
> 
> > The file looks something like this:
> 
> > 
> 
> > 1958 MGA Twin Cam
> 
> > 1958 Zunndapp Janus
> 
> > 1961 Amphicar
> 
> > 1961 Corvair
> 
> > 1966 Peel Trident
> 
> > 1970 AMC Gremlin
> 
> > 1970 Triumph Stag
> 
> > 1971 Chrysler Imperial LeBaron Two-Door Hardtop
> 
> > 
> 
> > The car manufacturer should be the key and a tuple containing the year and 
> 
> > the model should be the key's value. I tried the following to just get the 
> 
> > contents of the file into a list, but only the very last line in the txt 
> > file 
> 
> > is shown as a list with three elements (ie, ['2004', 'Chevy', 'SSR']) when 
> > I 
> 
> > print temp.
> 
> > 
> 
> > d={}
> 
> > car_file = open('worstcars.txt', 'r')
> 
> > for line in car_file:
> 
> > temp = line.split()
> 
> > print (temp)
> 
> > car_file.close()
> 
> 
> 
> Yup.  Because you run through the whole file, putting each line into 
> 
> temp, overwriting the previous temp value.
> 
> 
> 
> > d=[]
> 
> > car_file = open('worstcars.txt', 'r')
> 
> > for line in car_file:
> 
> > d.append(line.strip('\n'))
> 
> > print (d)
> 
> > car_file.close()
> 
> 
> 
> You could do most of that with just:
> 
> 
> 
> car_file = open('worstcars.txt', 'r')
> 
> d = car_file.readlines()
> 
> 
> 
> but there's no real reason to read the whole file into a list.  What you 
> 
> probably want to do is something like:
> 
> 
> 
> d = {}
> 
> car_file = open('worstcars.txt', 'r')
> 
> for line in car_file:
> 
>year, manufacturer, model = parse_line(line)
> 
>d[manufacturer] = (year, model)
> 
> 
> 
> One comment about the above; it assumes that there's only a single entry 
> 
> for a given manufacturer in the file.  If that's not true, the above 
> 
> code will only keep the last one.  But let's assume it's true for the 
> 
> moment.
> 
> 
> 
> Now, we're just down to writing parse_line().  This takes a string and 
> 
> breaks it up into 3 strings.  I'm going to leave this as an exercise for 
> 
> you to work out.  The complicated part is going to be figuring out some 
> 
> logic to deal with anything from multi-word model names ("Imperial 
> 
> LeBaron Two-Door Hardtop"), to lines like the Corvair where there is no 
> 
> manufacturer (or maybe there's no model?).

Roy, thank you so much! I'll do some more research to see how I can achieve 
this. Thank you!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread Chris Angelico
On Mon, Apr 1, 2013 at 4:19 AM, C.T.  wrote:
> Thank you, Chris! I could use slicing and indexing to build the dictionary 
> but the problem is with the car manufacturer an the car model. Either or both 
> could be multiple names.

Then you're going to need some other form of magic to recognize where
the manufacturer ends and the model starts. Do you have, say, tabs
between the fields and spaces within?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread C.T.
On Sunday, March 31, 2013 12:06:18 PM UTC-4, Chris Angelico wrote:
> On Mon, Apr 1, 2013 at 2:52 AM, C.T.
> 
> > After playing around with the code, I came up with the following code to 
> > get everything into a list:
> 
> >
> 
> > d=[]
> 
> > car_file = open('worstcars.txt', 'r')
> 
> > for line in car_file:
> 
> > d.append(line.strip('\n'))
> 
> > print (d)
> 
> > car_file.close()
> 
> >
> 
> > Every line is now an element in list d. The question I have now is how can 
> > I make a dictionary out of the list d with the car manufacturer as the key 
> > and a tuple containing the year and the model should be the key's value.
> 
> 
> 
> Ah, a nice straight-forward text parsing problem!
> 
> 
> 
> The question is how to recognize the manufacturer. Is it guaranteed to
> 
> be the second blank-delimited word, with the year being the first? If
> 
> so, you were almost there with .split().
> 
> 
> 
> car_file = open('worstcars.txt', 'r')
> 
> # You may want to consider the 'with' statement here - no need to close()
> 
> for line in car_file:
> 
> temp = line.split(None, 2)
> 
> if len(temp)==3:
> 
> year, mfg, model = temp
> 
> # Now do something with these three values
> 
> print("Manufacturer: %s  Year: %s  Model: %s"%(mfg,year,model))
> 
> 
> 
> That's sorted out the parsing side of things. Do you know how to build
> 
> up the dictionary from there?
> 
> 
> 
> What happens if there are multiple entries in the file for the same
> 
> manufacturer? Do you need to handle that?
> 
> 
> 
> ChrisA

Thank you, Chris! I could use slicing and indexing to build the dictionary but 
the problem is with the car manufacturer an the car model. Either or both could 
be multiple names. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread C.T.
On Sunday, March 31, 2013 12:20:25 PM UTC-4, zipher wrote:
> Every line is now an element in list d. The question I have now is how can I 
> make a dictionary out of the list d with the car manufacturer as the key and 
> a tuple containing the year and the model should be the key's value. Here is 
> a sample of what list d looks like:
> 
> 
> 
> 
> ['1899 Horsey Horseless', '1909 Ford Model T', '1911 Overland OctoAuto', 
> '2003 Hummer H2', '2004 Chevy SSR']
> 
> 
> 
> Any help would be appreciated!
> 
> 
> 
> 
> As long as your data is consistently ordered, just use list indexing.  d[2] 
> is your key, and (d[1],d[3]) the key's value.
> 
> 
> 
> Mark
> Tacoma, Washington


Thank you, Mark! My problem is the data isn't consistently ordered. I can use 
slicing and indexing to put the year into a tuple, but because a car 
manufacturer could have two names (ie, Aston Martin) or a car model could have 
two names(ie, Iron Duke), its harder to use slicing and indexing for those two. 
 I've added the following, but the output is still not what I need it to be.


t={}
for i in d :
t[d[d.index(i)][5:]]= tuple(d[d.index(i)][:4])

print (t)

The output looks something like this:

{'Ford Model T': ('1', '9', '0', '9'), 'Mosler Consulier GTP': ('1', '9', '8', 
'5'), 'Scripps-Booth Bi-Autogo': ('1', '9', '1', '3'), 'Morgan Plus 8 Propane': 
('1', '9', '7', '5'), 'Fiat Multipla': ('1', '9', '9', '8'), 'Ford Pinto': 
('1', '9', '7', '1'), 'Triumph Stag': ('1', '9', '7', '0'), 'BMW 7-series': 
('2', '0', '0', '2')}


Here the key is the car manufacturer and car model and the value is a tuple 
containing the year separated by a comma.( Not sure why that is ?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread Roy Smith
In article ,
 "C.T."  wrote:

> Hello,
> 
> I'm currently working on a homework problem that requires me to create a 
> dictionary from a .txt file that contains some of the worst cars ever made. 
> The file looks something like this:
> 
> 1958 MGA Twin Cam
> 1958 Zunndapp Janus
> 1961 Amphicar
> 1961 Corvair
> 1966 Peel Trident
> 1970 AMC Gremlin
> 1970 Triumph Stag
> 1971 Chrysler Imperial LeBaron Two-Door Hardtop
> 
> The car manufacturer should be the key and a tuple containing the year and 
> the model should be the key's value. I tried the following to just get the 
> contents of the file into a list, but only the very last line in the txt file 
> is shown as a list with three elements (ie, ['2004', 'Chevy', 'SSR']) when I 
> print temp.
> 
> d={}
> car_file = open('worstcars.txt', 'r')
> for line in car_file:
> temp = line.split()
> print (temp)
> car_file.close()

Yup.  Because you run through the whole file, putting each line into 
temp, overwriting the previous temp value.

> d=[]
> car_file = open('worstcars.txt', 'r')
> for line in car_file:
> d.append(line.strip('\n'))
> print (d)
> car_file.close()

You could do most of that with just:

car_file = open('worstcars.txt', 'r')
d = car_file.readlines()

but there's no real reason to read the whole file into a list.  What you 
probably want to do is something like:

d = {}
car_file = open('worstcars.txt', 'r')
for line in car_file:
   year, manufacturer, model = parse_line(line)
   d[manufacturer] = (year, model)

One comment about the above; it assumes that there's only a single entry 
for a given manufacturer in the file.  If that's not true, the above 
code will only keep the last one.  But let's assume it's true for the 
moment.

Now, we're just down to writing parse_line().  This takes a string and 
breaks it up into 3 strings.  I'm going to leave this as an exercise for 
you to work out.  The complicated part is going to be figuring out some 
logic to deal with anything from multi-word model names ("Imperial 
LeBaron Two-Door Hardtop"), to lines like the Corvair where there is no 
manufacturer (or maybe there's no model?).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread Mark Janssen
>
> Every line is now an element in list d. The question I have now is how can
> I make a dictionary out of the list d with the car manufacturer as the key
> and a tuple containing the year and the model should be the key's value.
> Here is a sample of what list d looks like:
>
> ['1899 Horsey Horseless', '1909 Ford Model T', '1911 Overland OctoAuto',
> '2003 Hummer H2', '2004 Chevy SSR']
>
> Any help would be appreciated!
>
>
As long as your data is consistently ordered, just use list indexing.  d[2]
is your key, and (d[1],d[3]) the key's value.

Mark
Tacoma, Washington
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary from a .txt file

2013-03-31 Thread Chris Angelico
On Mon, Apr 1, 2013 at 2:52 AM, C.T.  wrote:
> After playing around with the code, I came up with the following code to get 
> everything into a list:
>
> d=[]
> car_file = open('worstcars.txt', 'r')
> for line in car_file:
> d.append(line.strip('\n'))
> print (d)
> car_file.close()
>
> Every line is now an element in list d. The question I have now is how can I 
> make a dictionary out of the list d with the car manufacturer as the key and 
> a tuple containing the year and the model should be the key's value.

Ah, a nice straight-forward text parsing problem!

The question is how to recognize the manufacturer. Is it guaranteed to
be the second blank-delimited word, with the year being the first? If
so, you were almost there with .split().

car_file = open('worstcars.txt', 'r')
# You may want to consider the 'with' statement here - no need to close()
for line in car_file:
temp = line.split(None, 2)
if len(temp)==3:
year, mfg, model = temp
# Now do something with these three values
print("Manufacturer: %s  Year: %s  Model: %s"%(mfg,year,model))

That's sorted out the parsing side of things. Do you know how to build
up the dictionary from there?

What happens if there are multiple entries in the file for the same
manufacturer? Do you need to handle that?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Creating a dictionary from a .txt file

2013-03-31 Thread C.T.
Hello,

I'm currently working on a homework problem that requires me to create a 
dictionary from a .txt file that contains some of the worst cars ever made. The 
file looks something like this:

1958 MGA Twin Cam
1958 Zunndapp Janus
1961 Amphicar
1961 Corvair
1966 Peel Trident
1970 AMC Gremlin
1970 Triumph Stag
1971 Chrysler Imperial LeBaron Two-Door Hardtop

The car manufacturer should be the key and a tuple containing the year and the 
model should be the key's value. I tried the following to just get the contents 
of the file into a list, but only the very last line in the txt file is shown 
as a list with three elements (ie, ['2004', 'Chevy', 'SSR']) when I print temp.

d={}
car_file = open('worstcars.txt', 'r')
for line in car_file:
temp = line.split()
print (temp)
car_file.close()

After playing around with the code, I came up with the following code to get 
everything into a list:

d=[]
car_file = open('worstcars.txt', 'r')
for line in car_file:
d.append(line.strip('\n'))
print (d)
car_file.close()

Every line is now an element in list d. The question I have now is how can I 
make a dictionary out of the list d with the car manufacturer as the key and a 
tuple containing the year and the model should be the key's value. Here is a 
sample of what list d looks like:

['1899 Horsey Horseless', '1909 Ford Model T', '1911 Overland OctoAuto', '2003 
Hummer H2', '2004 Chevy SSR']

Any help would be appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary

2012-10-09 Thread Ulrich Eckhardt

Am 09.10.2012 13:59, schrieb arg...@gmail.com:

below is the text file i have How to create Facility as a key and then assign 
multiple values to it


The value part of a dict element can be any kind of object, like e.g. a 
tuple, namedtuple or even a dict.



Uli

--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary

2012-10-09 Thread Roy Smith
In article <50741ffe$0$6574$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> On Tue, 09 Oct 2012 04:59:49 -0700, argbsk wrote:
> 
> > below is the text file i have How to create Facility as a key and then
> > assign multiple values to it
> 
> To use Facility as a key in a dict:
> 
> d = {}
> d['Facility'] = 'ham'
> 
> Note that keys are case-sensitive, so that 'Facility', 'facility', 
> 'FACILITY' and 'FaCiLiTy' are all different.
> 
> To have multiple values assigned to a key, use a list:
> 
> d['Facility'] = ['ham', 'spam', 'cheese', 'eggs']
> d['Facility'].append('tomato')

I think what he really wants to end up with is a dictionary of 
dictionaries:

{'BACKUP': {'Total' : 34,
 'Passed' : 32,
 'Failed' : 2,
 'Not Run' : 0
  },
 'CDU': {}
}

Or, somewhat more work, but a richer solution, create a FacilityData 
class, whose attributes are total, passed, failed, not_run, etc, and 
have instances of FacilityData be the values.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a dictionary

2012-10-09 Thread Steven D'Aprano
On Tue, 09 Oct 2012 04:59:49 -0700, argbsk wrote:

> below is the text file i have How to create Facility as a key and then
> assign multiple values to it

To use Facility as a key in a dict:

d = {}
d['Facility'] = 'ham'

Note that keys are case-sensitive, so that 'Facility', 'facility', 
'FACILITY' and 'FaCiLiTy' are all different.

To have multiple values assigned to a key, use a list:

d['Facility'] = ['ham', 'spam', 'cheese', 'eggs']
d['Facility'].append('tomato')



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Creating a dictionary

2012-10-09 Thread argbsk
below is the text file i have How to create Facility as a key and then assign 
multiple values to it

FACILITY : BACKUP
FAILED BACKUP_BEFORE
FAILED BACKUP_INTERCHANGE
Total : 34
Passed : 32
Failed : 2
Not Run : 0

FACILITY : CDU
Total : 9
Passed : 9
Failed : 0


for example Facility BACKUP is a key & its values are Total Passed, Failed Not 
Run and Facility CDU as a key & its values Total:9,Passed:9,Failed:0 etc...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating a dictionary from a dictionary with regex

2007-08-22 Thread Marc 'BlackJack' Rintsch
On Wed, 22 Aug 2007 07:13:40 +, james_027 wrote:

> I am trying to create a dictionary from a dictionary which the help of
> regex to identify which keys to select. I have something like this but
> I feel its long and not the fastest solution ... could someone
> contribute?
> 
> import re
> 
> d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12, 'line2.item':'5c-BL
> Battery', 'line3.item':'N73', 'line5.item':'Screen Cover'}
> 
> collected = [k[:5] for k in d if re.match('^line\d+\.qty',k)]
> 
> for i in collected:
> d2 = {}
> for k in d:
> if re.match('^%s\.\D+' % i, k):
> d2[k] = d[k]
> print d2

You are iterating over `d` for every item in `collected`.  With another
`dict` to store the results you can iterate over `d` only once:

from collections import defaultdict

def main():
d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12,
'line2.item':'5c-BL Battery', 'line3.item':'N73',
'line5.item':'Screen Cover'}

result = defaultdict(dict)
for key, value in d.iteritems():
new_key = key.split('.', 1)[0]  # Get the 'line#' part.
result[new_key][key] = value
print result

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


creating a dictionary from a dictionary with regex

2007-08-22 Thread james_027
Hi,

I am trying to create a dictionary from a dictionary which the help of
regex to identify which keys to select. I have something like this but
I feel its long and not the fastest solution ... could someone
contribute?

import re

d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12, 'line2.item':'5c-BL
Battery', 'line3.item':'N73', 'line5.item':'Screen Cover'}

collected = [k[:5] for k in d if re.match('^line\d+\.qty',k)]

for i in collected:
d2 = {}
for k in d:
if re.match('^%s\.\D+' % i, k):
d2[k] = d[k]
print d2

Thanks
james

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating a dictionary

2007-01-29 Thread Gabriel Genellina
En Mon, 29 Jan 2007 23:45:40 -0300, mark <[EMAIL PROTECTED]> escribió:

> i have few variables and i want to create a dictionary with these  
> variables
> such that the keys are the variable names and the corresponding values
> are the variable values.how do i do this easily?
> for ex:
> var1='mark'
> var2=['1','2','3']
> my_dict = create_my_dictionary(var1, var2)
>
> and my_dict is {'var1':'mark', 'var2':['1','2','3']}
>
> is there a function for create_my_dictionary?

var1='mark'
var2=['1','2','3']
my_dict = dict(var1=var1, var2=var2)

In addition, if you are inside a function, and these are the only  
variables, using locals() may be useful too:

def f():
   a = 1
   b = 2
   c = locals()
   print c
   d = 3

prints {'a': 1, 'b': 2}

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


creating a dictionary

2007-01-29 Thread mark

i have few variables and i want to create a dictionary with these variables
such that the keys are the variable names and the corresponding values
are the variable values.how do i do this easily?
for ex:
var1='mark'
var2=['1','2','3']
my_dict = create_my_dictionary(var1, var2)

and my_dict is {'var1':'mark', 'var2':['1','2','3']}

is there a function for create_my_dictionary?
-- 
http://mail.python.org/mailman/listinfo/python-list