Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
SurgicalOntologist
Jun 17, 2004

Squack McQuack posted:

1. Since I'm new to programming, I never considered the game running its update functions at different rates on different computers. One of my classes contains the main game's sprites. The update function for this class applies gravity when the sprite is jumping. On my computer, this was applied 60 times per second. I tested on another computer though, and it seems to be applied at a much faster rate, which results in the sprite barely jumping off the ground.


Not sure about Cocos2D, but in pyglet, the callback should take only one argument, dt, which is the amount of time that is passed since the callback was previously called. Use a formula for gravity that explicitly uses time.

Unless Cocos2D offers something else, you should be doing something like:

Python code:
def apply_gravity(dt):
    ...


pyglet.clock.schedule(apply_gravity)
pyglet.app.run()

Adbot
ADBOT LOVES YOU

Squack McQuack
Nov 20, 2013

by Modern Video Games

SurgicalOntologist posted:

Not sure about Cocos2D, but in pyglet, the callback should take only one argument, dt, which is the amount of time that is passed since the callback was previously called. Use a formula for gravity that explicitly uses time.

Unless Cocos2D offers something else, you should be doing something like:

Python code:
def apply_gravity(dt):
    ...


pyglet.clock.schedule(apply_gravity)
pyglet.app.run()

OK, that's starting to make sense. Right now the "game sprites" class has an update function that includes a lot of stuff, including gravity:
code:
GRAVITY = 200

class Game_sprites(cocos.layer.Layer):

    def __init__(self):
        # A whole bunch of stuff, then...
        self.schedule(self.update)

    def update(self, dt):
        # A whole bunch of stuff, then...
        if self.player.is_jumping:
            fall_rate -= GRAVITY
            self.player.velocity = 0, fall_rate
I'm unclear on the difference between "self.schedule()" and "pyglet.clock.schedule()". Also, I still don't quite get how this will help if different computers are calling update at different rates. Does the solution have to do with what you said here?

SurgicalOntologist posted:

Use a formula for gravity that explicitly uses time.

SurgicalOntologist
Jun 17, 2004

Squack McQuack posted:

I'm unclear on the difference between "self.schedule()" and "pyglet.clock.schedule()".

It appears it works the same way, I just wasn't familiar with Cocos2D. You can pretty much ignore my code example.

Squack McQuack posted:

Also, I still don't quite get how this will help if different computers are calling update at different rates. Does the solution have to do with what you said here?

Yes. The parameter dt is the amount of time that's passed since the last update call. If you want the sprite's behavior to depend on clock time, not frequency of calling updates, then you need to use this parameter in some way. In your code you are not using dt.

Think about the units that your GRAVITY variable has. Pixels per second squared I would guess. In other words change in velocity (pixels per second) per second. At least that's what it should be. But you decrement fall_rate by 200 every time update is called. So your GRAVITY variable actually has units of pixels per second per update call. What you want is this:

Python code:
fall_rate -= GRAVITY * dt 
So if update is being called once per second, or ten times per second, fall_rate will change at the same rate. Indeed you want to multiply by dt every time you are applying a rate in a callback. (Not sure if velocity is built-in to Cocos2D or if you are using it to change position in another callback. If the latter you will also need to multiply by dt there)

Squack McQuack
Nov 20, 2013

by Modern Video Games

SurgicalOntologist posted:

So if update is being called once per second, or ten times per second, fall_rate will change at the same rate. Indeed you want to multiply by dt every time you are applying a rate in a callback. (Not sure if velocity is built-in to Cocos2D or if you are using it to change position in another callback. If the latter you will also need to multiply by dt there)

Great, I think I get it. I'll give it a try later tonight and report back. Thanks!

Edit: That did it! Thanks a lot, it would have taken me so long to solve that on my own. I'm still having a problem with #2 unfortunately. So far I've gotten it to work on 2 computers (Win7 and Win8) and failed on one (Win7). Maybe it has to do with the capability of the hardware? The failed computer is fairly old, from 2008 or so.

quote:

2. I want to convert this game to an exe file so others can play it. I did this using PyInstaller, and got the exe file to run successfully on my own computer. I ran into trouble on another computer, though. The game runs but there's a weird graphical glitch - there's one sprite that is displayed as a white block.

Squack McQuack fucked around with this message at 02:19 on Jul 8, 2014

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."
Is there a way to open and close URL sessions multiple times in the same program?

I have a URL that returns a JSON depending on the ID number given. I need to go through about 4000 of these. Right now the server times out after ~100 iterations of a for loop. What can I do to do bursts of data collection and spit it all out to one file?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

raej posted:

Is there a way to open and close URL sessions multiple times in the same program?

I have a URL that returns a JSON depending on the ID number given. I need to go through about 4000 of these. Right now the server times out after ~100 iterations of a for loop. What can I do to do bursts of data collection and spit it all out to one file?

Python code:
import requests

with open('my_file.txt', 'w') as f:
    for url in list_of_4000_urls:
        f.write(requests.get(url))
Note that I'm using the excellent requests library. If you don't want to use that then use python's weaksauce urllib2 or whatever.

I'm not sure I understood your question, so this might not be what you're looking for.

Dominoes
Sep 20, 2007

Yea use requests. I dunno what you're doing exactly, but something like this should work:

Python code:
def incr(ids, url):
    inc = 100
    start, end = 0, inc
    for i in range(math.ceil(len(ids) / inc)):
        set_ = ids[start: end]
        payload = {'target': 'ISIS_mainframe', 'requested_data': set_}
        yield requests.post(url, data=payload).json()
        start = end
        end += inc


result = []
for i in incr(ids, url):
    if i:
        result.extend(incr)

Dominoes fucked around with this message at 17:28 on Jul 8, 2014

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."
http://www.ratebeer.com/json/bi.asp?k=tTmwRTWT-W7tpBhtL&b=[ID]

This url spits out the JSON for that brewery.

I was originally doing a for loop that went from [ID] 1 to 1000, but like I said, that was timing out. I was also doing it in PHP which was probably a stupid idea.

Space Kablooey
May 6, 2009


GET requests can time out, but they shouldn’t time out because you took a long time between two of them.

This is working:

Python code:
# coding: UTF-8
import requests


for i in range(1001):
    print i
    response = requests.get('http://www.ratebeer.com/json/bi.asp?k=tTmwRTWT-W7tpBhtL&b=' + str(i))
    print response.ok
    try:
        print response.json()
    except ValueError:
        pass
I'm really not sure what's going on on your end.

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."

HardDisk posted:

GET requests can time out, but they shouldn’t time out because you took a long time between two of them.

This is working:

Python code:
# coding: UTF-8
import requests


for i in range(1001):
    print i
    response = requests.get('http://www.ratebeer.com/json/bi.asp?k=tTmwRTWT-W7tpBhtL&b=' + str(i))
    print response.ok
    try:
        print response.json()
    except ValueError:
        pass
I'm really not sure what's going on on your end.

Thanks! I tried this out, and since it's starting with 0 (which times out) I receive an error. How would I set a start and end number to iterate through? Adding in "i=16000" before the for loop still spits out 0 when it runs.

Dominoes
Sep 20, 2007

raej posted:

Thanks! I tried this out, and since it's starting with 0 (which times out) I receive an error. How would I set a start and end number to iterate through? Adding in "i=16000" before the for loop still spits out 0 when it runs.
Python code:
for i in range(69, 1001):
First argument for range() is the start index, second is one after* the end. Optional third lets you set an interval other than 1, ie jump that many indexes each iteration.

* Anyone know why?

Dominoes fucked around with this message at 21:50 on Jul 8, 2014

Lyon
Apr 17, 2003

Dominoes posted:

Python code:
for i in range(69, 1001):

First argument for range() is the start index, second is one after* the end. Optional third lets you set an interval other than 1, ie jump that many indexes each iteration.

* Anyone know why?

I think so you can do len(whatever) instead of len(whatever) - 1.

SurgicalOntologist
Jun 17, 2004

Dominoes posted:

First argument for range() is the start index, second is one after* the end. Optional third lets you set an interval other than , ie skip that many indexes each iteration.

* Anyone know why?

It's the same way slices work, and it's tied into the choice of zero-based indexing. The other choice, besides zero- or one-based indexing, is whether the interval is closed or open, and Python uses half-open intervals (open on the left, closed on the right), which is what we see with range. Part of the reason for choosing zero-based indexing is because one-based doesn't really work with half-open intervals, and half-open intervals are elegant.

https://plus.google.com/115212051037621986145/posts/YTUxbXYZyfi

Why are half-open intervals elegant? Well, for one, len(range(start, end)) = end - start. For another, if you want to have two ranges that connect, you can do first, second = range(end//2), range(end//2, end) (if end is even, in this example). In other words you pick up where you previously left off without doing a +1.

With any indexing choice you will have to do +1 or -1 in some cases, in Python where that comes up is with range if you know the last number you want, you have to do +1. But with something like Matlab with open intervals and one-based indexing, you have to do +/- 1 all the loving time and people always get it wrong and make off-by-one errors.



By the way, does anyone have a Chrome plugin or AutoHotKey script or anything that makes a shortcut to insert [fixed][/fixed] around a selection? I am sick and tired of typing that.

Master_Odin
Apr 15, 2010

My spear never misses its mark...

ladies

SurgicalOntologist posted:

By the way, does anyone have a Chrome plugin or AutoHotKey script or anything that makes a shortcut to insert [fixed][/fixed] around a selection? I am sick and tired of typing that.
In the Quick Reply box in SALR, if you hit Ctrl+F when you've selected text, it'll warp it in the fixed tags.

SurgicalOntologist
Jun 17, 2004

Master_Odin posted:

In the Quick Reply box in SALR, if you hit Ctrl+F when you've selected text, it'll warp it in the fixed tags.

Good to know, thanks. I disabled the Quick Reply box before I started posting code often, for some long-forgotten reason. This is a good reason to re-enable it.

QuarkJets
Sep 8, 2008

Dominoes posted:

Python code:
for i in range(69, 1001):
First argument for range() is the start index, second is one after* the end. Optional third lets you set an interval other than 1, ie jump that many indexes each iteration.

* Anyone know why?

Because range(N) spits out a list that doesn't include N, so it wouldn't make sense for the list produced by range(A, B) to include B, either. They probably would include the provided value if Python counted from 1 instead of 0 (but that would be terrible for other reasons)

Dominoes
Sep 20, 2007

Thanks for the explanations.

SurgicalOntologist posted:

With any indexing choice you will have to do +1 or -1 in some cases, in Python where that comes up is with range if you know the last number you want, you have to do +1. But with something like Matlab with open intervals and one-based indexing, you have to do +/- 1 all the loving time and people always get it wrong and make off-by-one errors.
I converted a Matlab frequency-detection algorithm to Python once - most of the trouble was putting +/-1s in the right places.

Carrier
May 12, 2009


420...69...9001...
Why is this code not working? I've been looking at it for ages now with glazed eyes aha. In python 3.4 if that info is needed.
code:
def rand_dict(data):
	upper_lim = float(input("Generate Random numbers between 0 and: "))
	length = int(input("Length of list: "))
	LList = [ i for i in range(1, length+1)]
	RList = [(upper_lim*random.random()) for i in range(1,length+1)]
	data = dict(zip(LList,RList))
	print(data)
data_list = {}
while True:
	if menu_choice == 1:
		rand_dict(data_list)
		print(data_list)
		print("Random Data Generated")

When I run this code (with the appropriate things imported) the printed list in the rand_dict function prints the dictionary as expected, but when I print data_list separately it gives me the empty dictionary.:

code:
Generate Random numbers between 0 and: 10
Length of list: 5
{1: 1.3793579670626088, 2: 7.405704968849681, 3: 3.025338220505306, 4: 3.887520371487879, 5: 6.225437458076621}
{}
Random Data Generated

Telarra
Oct 9, 2012

When you do:

code:
data = dict(zip(LList,RList))
it creates a new dict and assigns it to 'data', but 'data_list' in the calling scope still refers to the empty list you assigned it.

Passing in a value to be filled with data as an argument like that seems like a habit from C/C++; perhaps try having the 'rand_dict' function return the data instead?

FoiledAgain
May 6, 2007

Carrier posted:

Why is this code not working? I've been looking at it for ages now with glazed eyes aha. In python 3.4 if that info is needed.

I think what the above post says is correct. But even then I would wonder why you need rand_dict() to take any arguments at all, since you're sending it an empty dictionary every time anyway. Something like this maybe:

code:
def rand_dict():
	upper_lim = float(input("Generate Random numbers between 0 and: "))
	length = int(input("Length of list: "))
	LList = [ i for i in range(1, length+1)]
	RList = [(upper_lim*random.random()) for i in range(1,length+1)]
	data = dict(zip(LList,RList))
	return data

while True:
	if menu_choice == 1:
		data_list = rand_dict()
		print(data_list)
		print("Random Data Generated")

Carrier
May 12, 2009


420...69...9001...
Ahh thank you! I've just come off of a couple of days full of C so I think you are right in where that particular habit came from!

the
Jul 18, 2004

by Cowcaster
I'm having to go through and clean some data that I grabbed. A lot of them have unicode characters that pop errors, for example:

Python code:
UnicodeEncodeError: 'ascii' codec can't encode character u'\x8e' in position 6: ordinal not in range(128)
And to fix this I have a "cleaner" definition that I've been continuously making longer and longer with each unicode error that pops up:

Python code:
def unicodecleaner(k):
	k = k.replace(u'\xc1','')
	k = k.replace(u'\xf3n','')
	k = k.replace(u'\xf4','')
	k = k.replace(u'\xa0','')
	k = k.replace(u'\xe2','')
	k = k.replace(u'\x80','')
	k = k.replace(u'\x8b','')
	k = k.replace(u'\xa8','')
	k = k.replace(u'\x8e','')
	cleaned = str(k)
	return cleaned
Is there a better way to do this? I just want the string out of there with all the unicode poo poo removed. It's just a list of zip codes.

SurgicalOntologist
Jun 17, 2004

I had a similar problem and used the unidecode library, which for example will replace an accented character with the closest ascii character. If you just want to delete the unicode characters it's probably easier. For example if you import string you will find string.digits, you can remove all characters that aren't in that.

Telarra
Oct 9, 2012

Or use this one-liner to remove all non-ascii characters:
Python code:
def unicodecleaner(k):
    return ''.join(i for i in k if ord(i) < 128)

the
Jul 18, 2004

by Cowcaster
Shouldn't it be less than or equal to 128? or is it 0 - 127?

Telarra
Oct 9, 2012

Yup, 0 - 127. You can even see it in the exception you posted:

Python code:
UnicodeEncodeError: 'ascii' codec can't encode character u'\x8e' in position 6: ordinal not in range(128)
range(128) yields 0 - 127

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

the posted:

Python code:
UnicodeEncodeError: 'ascii' codec can't encode character u'\x8e' in position 6: ordinal not in range(128)

Where and why are you trying to encode internationalized text as ASCII? Are you absolutely sure that you need to do this?

Jose Cuervo
Aug 25, 2004
I have a .py file named transpose_plans.py located in "C:\\JCuervo\\work\\analysis" and I want the text files output to be located in "C:\\JCuervo\\work\\repast\\cplans\\york\\output\\".

Is this the best way to get the relative(?) path from transpose_plans.py to the output folder:
Python code:
data_path= os.path.join(os.path.dirname('transpose_plans.py'), '..',
            'repast\cplans\york\output\\')
or is there a better way?

SurgicalOntologist
Jun 17, 2004

Jose Cuervo posted:

I have a .py file named transpose_plans.py located in "C:\\JCuervo\\work\\analysis" and I want the text files output to be located in "C:\\JCuervo\\work\\repast\\cplans\\york\\output\\".

Is this the best way to get the relative(?) path from transpose_plans.py to the output folder:
Python code:
data_path= os.path.join(os.path.dirname('transpose_plans.py'), '..',
            'repast\cplans\york\output\\')
or is there a better way?

Did you try it? I think you'll find that os.path.dirname('transpose_plans.py') will return an empty string. It returns the directory component of a path, the path 'transpose_plans.py' has no directory component.

What's the best way depends on a lot of things. Will this ever get run on a different filesystem? Different absolute paths? Different OSes? If not, just hardcode the output folder and be done with it, maybve set it at the top of the script as a constant so you can easily find it again if you want to change it in a year.

If the answer to those questions is a yes, then you can start thinking of the "best" way. I suppose you would have to decide if you want the output directory to be defined invariantly in relation to the script itself, or to some input directory/file.

the
Jul 18, 2004

by Cowcaster

Lysidas posted:

Where and why are you trying to encode internationalized text as ASCII? Are you absolutely sure that you need to do this?

All I know is I'm grabbing zip codes via SQL request from US/Canada and trying to store them in a list in Python. I have no earthly idea where the weird codes are coming from.

For some reason some of the zipcodes will come out like

code:
u'\xa034241\x80'

tef
May 30, 2004

-> some l-system crap ->

the posted:

I'm having to go through and clean some data that I grabbed. A lot of them have unicode characters that pop errors, for example:

Python code:
UnicodeEncodeError: 'ascii' codec can't encode character u'\x8e' in position 6: ordinal not in range(128)
Is there a better way to do this? I just want the string out of there with all the unicode poo poo removed. It's just a list of zip codes.

SurgicalOntologist posted:

I had a similar problem and used the unidecode library, which for example will replace an accented character with the closest ascii character

Moddington posted:

Or use this one-liner to remove all non-ascii characters:

if you're desperate to get a string out of a sequence of mostly ascii, you can use '\xa034241\x80'.decode('ascii', 'ignore') in py2.
u'34241'

Lysidas posted:

Where and why are you trying to encode internationalized text as ASCII? Are you absolutely sure that you need to do this?

This is the more important question — how are you getting your data? you might find that you will need to set an encoding somewhere, which will actually fix your problem

the
Jul 18, 2004

by Cowcaster

tef posted:

This is the more important question — how are you getting your data? you might find that you will need to set an encoding somewhere, which will actually fix your problem

I'm using Beatbox to query a database in Salesforce. I'm grabbing a list of Account zip code fields. They get returned as type 'instance' and I convert them to a string before doing anything with them.

Which leads to my next question: I need to be able to check to see if the entries are blank. Some of them didn't have zip codes, so nothing was written in the zip code portion of the column:

code:
In [2]: map_list[1]
Out[2]: ['Account', '32073-5729']

In [3]: map_list[2]
Out[3]: ['Account', '22192']

In [4]: map_list[3]
Out[4]: ['Account']

In [5]: map_list[4]
Out[5]: ['Account', '57005']

In [6]: map_list[5]
Out[6]: ['Account', '61443']

In [7]: map_list[6]
Out[7]: ['Account', '12147']

In [8]: map_list[7]
Out[8]: ['Account']
I just want to get rid of those. I need to have something that says like "for i in maplist: if i[1] doesn't exist don't write it to the next list"

How can I do that?

edit: Ended up doing this:

code:
zipcode_list = []

for i in map_list:
	try:
		zipcode_list.append(i[1])
	except IndexError:
		pass

the fucked around with this message at 03:44 on Jul 11, 2014

SurgicalOntologist
Jun 17, 2004

The first step of whatever you're doing should be to turn those records into dictionaries so you could refer to the fields by name like God intended. Either you did something wrong along the way or that is a terrible API. I'm pretty sure it's the latter. Point is, patch the leak first by turning those lists into dictionaries. Handle the missing data during that process.

BabyFur Denny
Mar 18, 2003
Hi,
I am new to python (and programming in general) but so far I am a huge fan of python.
Right now I am tinkering with tkinter, and I ran into a problem.

code:
from tkinter import *

elements = []
class Zahl():
    def __init__(self, name, Beschreibung):
        self.name = name
        self.Beschreibung = Beschreibung
        elements.append(self)
        
    def sel(self):
        selection = "You selected the option " + self.Beschreibung
        label.config(text = selection)

        


Eins = Zahl('Eins','Eine Eins')
Zwei = Zahl('Zwei','Eine Zwei')
Drei = Zahl('Drei','Eine Drei')
Zahlen = [Eins, Zwei, Drei]



def generiereButtons(elements):
    root = Tk()  
    for element in elements:  
        Radiobutton(root, text=element.name,  value=element.name,
                     command=element.sel,indicatoron=0).pack( anchor = W )

    label = Label(root)
    label.pack()
    elements[0].sel()
    root.mainloop()
    
generiereButtons(Zahlen)
I have several objects of a class and I want to show radio buttons to select one of those objects.
My goal is to have a function generiereButtons that I can pass an array of classes and it builts the radio buttons for each element.
If I run the code inside the generiereButtons function without the function itself, it works fine, but if I put it in a function it no longer works, because Zahl.sel() tries to access label which does not exist outside the scope of generiereButton, if I understood that correctly.
If I try to pass "label" with sel(label) I get an error because label is defined after the radio buttons. If I define label as a global var I probably cannot reuse the generiereButton function in several places without running into trouble at some point.
How do I organise my code and functions to make this work? I haven't had any formal IT education so it's still difficult for me to come up with a proper hierarchical structure.

FoiledAgain
May 6, 2007

BabyFur Denny posted:

Hi,
I am new to python (and programming in general) but so far I am a huge fan of python.
Right now I am tinkering with tkinter, and I ran into a problem.

Make an "App" object (or a "GUI" or "Program" or whatever). Any information that you want shared between methods becomes an attribute of the App. So in your case, something like this:

code:
from tkinter import *
import tkinter.messagebox as MessageBox

class App(Toplevel):

    def __init__(self,master):
        super(App, self).__init__(master)#this is Python 3, don't know about Python 2
        self.elements = [Zahl('Eins','Eine Eins'), Zahl('Zwei','Eine Zwei'), Zahl('Drei','Eine Drei')]
        self.zahl_var = StringVar()#you should google "tkinter variables" if you don't know about these yet
        self.generiereButtons()

    def generiereButtons(self):
        button_frame = LabelFrame(self, text='Click a button!')
        for element in self.elements:
            r = Radiobutton(button_frame, text=element.name, variable=self.zahl_var, value=element.Beschreibung, command=self.show_selection)
            r.pack()
        button_frame.pack()

    def show_selection(self):
        selection = self.zahl_var.get()
        MessageBox.showinfo(message='You selected '+selection)


class Zahl():
    def __init__(self, name, Beschreibung):
        self.name = name
        self.Beschreibung = Beschreibung


if __name__ == '__main__':

    root = Tk()
    app = App(root)
    root.mainloop()
    

BabyFur Denny
Mar 18, 2003
Ok, thanks for that, and I think I made some progress in understanding the whole thing.

But the way you set up show_selection, I cannot do anything with the selected class, since the function only has access to zahl_var and it's value, not the actual class. If I try to pass the class to show_selection via command=self.show_selection(element) in the radio button (and of course using def show_selection(self, element): it no longer works.

And I haven't found out how to switch the messagebox for a label that can be updated in show_selection.

Here's the non-working code
code:
from tkinter import *
import tkinter.messagebox as MessageBox

class App(Toplevel):

    def __init__(self,master):
        super(App, self).__init__(master)#this is Python 3, don't know about Python 2
        self.elements = [Zahl('Eins','Eine Eins'), Zahl('Zwei','Eine Zwei'), Zahl('Drei','Eine Drei')]
        self.zahl_var = StringVar()#you should google "tkinter variables" if you don't know about these yet
        self.zahl_var.set(self.elements[0].Beschreibung)
        self.generiereButtons()

    def generiereButtons(self):
        button_frame = LabelFrame(self, text='Click a button!')
        label = Label(button_frame,textvariable = self.zahl_var)
        for element in self.elements:
            r = Radiobutton(button_frame, text=element.name, variable=self.zahl_var, value=element.Beschreibung, command=self.show_selection(element,label))
            r.pack()
        label.pack()
        button_frame.pack()

    def show_selection(self, element, label):
        selection = self.zahl_var.get()
        label.config(text = selection) 
        MessageBox.showinfo(message='You selected '+selection)


class Zahl():
    def __init__(self, name, Beschreibung):
        self.name = name
        self.Beschreibung = Beschreibung


if __name__ == '__main__':

    root = Tk()
    app = App(root)
    root.mainloop()

the
Jul 18, 2004

by Cowcaster

SurgicalOntologist posted:

The first step of whatever you're doing should be to turn those records into dictionaries so you could refer to the fields by name like God intended. Either you did something wrong along the way or that is a terrible API. I'm pretty sure it's the latter. Point is, patch the leak first by turning those lists into dictionaries. Handle the missing data during that process.

I have a problem of "I never work with dictionaries so I have no idea how to implement them so I never work with dictionaries."

How would it help in this case?

namaste friends
Sep 18, 2004

by Smythe
Dictionaries are one of the best things about Python :( .

the
Jul 18, 2004

by Cowcaster
Yeah I keep hearing that, I guess I never use them enough to really understand their worth.

So, as I understand it, it's a list that uses a key for output, right? That seems useful in a situation when I have multiple items associated with one unique entry (I know SurgicalOntologist has probably brought this up before when I've talked about the same work I'm doing).

Adbot
ADBOT LOVES YOU

SurgicalOntologist
Jun 17, 2004

the posted:

I have a problem of "I never work with dictionaries so I have no idea how to implement them so I never work with dictionaries."

How would it help in this case?

You could do something like record['zip'] or record['name'] (or e.g. record.get('zip') if some records don't have zips) instead of always remembering that e.g. record[1] is the zip code, etc.

Edit: or records[id_to_find]['zip'] if you have a dictionary of records, which are themselves dictionaries.

the posted:

Yeah I keep hearing that, I guess I never use them enough to really understand their worth.

So, as I understand it, it's a list that uses a key for output, right? That seems useful in a situation when I have multiple items associated with one unique entry (I know SurgicalOntologist has probably brought this up before when I've talked about the same work I'm doing).

Dictionaries are mappings from keys to values. The only connection to a list is that both lists and dicts can store multiple things. Don't think of them list lists, think of them like look-up tables.

If you have multiple items associated with the same key, then you could map keys to lists. If those multiple items are themselves well-represented by a dict, you could map keys to smaller dictionaries.

Think about how you would find specific record if everything was lists?

Python code:
for record in records:
    if record[0] == id_to_find:
        if len(record) > 1:
            zip_i_want = record[1]
        else
            zip_i_want = None
        break
compared to

Python code:
zip_i_want = records.get(id_to_find, {}).get('zip')

SurgicalOntologist fucked around with this message at 16:41 on Jul 11, 2014

  • Locked thread