Get value from query string in Python 3 without the [' '] showing up in the value - python-3.x

I have the following code in a Python 3 http server parse out a URL and then parse out a query string:
parsedURL = urlparse(self.path)
parsed = parse_qs(parsedURL.query)
say that parsedURL.query in this case turns about to be x=7&=3.I want to get the 7 and the 3 out and set them equal to variables x and y. I've tried both
x = parsed['x']
y = parsed['y']
and
x = parsed.get('x')
y = parsed.get('y')
both of these solutions come up with x = ['7'] and y = ['3'] but I don't want the brackets and single quotes, I want just the values 7 and 3, and I want them to be integers. How do I get the values out and get rid of the brackets/quotes?

Would simply:
x = int(parsed['x'][0])
y = int(parsed['y'][0])
or
x = int(parsed.get('x')[0])
y = int(parsed.get('y')[0])
serve your purpose? You should of course have suitable validation checks, but all you want to do is convert the first element of the returned array to an int, so this code will do the business.
This is because the get() returns an array of values (I presume!) so if you try parsing url?x=1&x=2&x=foo you would get back a list like ['1', '2', 'foo']. Normally there is only one (or zero, of course) instance of each variable in a query string, so we just grab the first entry with [0].
Note the documentation for parse_qs() says:
Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.

Related

How to fix list assignment index out of range error even after appending the array

I'm trying to get user's input through the entry widget into an array, keep note that the user's input is a number. How can I get the users input as an integer.
I tried changing the entry values to int with int(g.get())
but it gives me this line:
...
ValueError: invalid literal for int() with base 10: ''
...
So I tried putting it as a string first with int(str(g.get())
But that gave me the same error line.
Tried it outside the loop to get the values in the array, inside the loop, both, nothing worked.
I'm also not sure if my input into an array algorithm works, I'm thinking I might need to put the widget inside the array(?).
x = 6
ind = np.arange(N)
arr = []
G = tk.Entry(self, textvariable="")
G.pack
while x >= 0:
arr[x] = int(str(G.get()))
arr.append(x)
x = x - 1
I expect to have an array of numbers that the user inputted into the entry widget, for example, arr = [6,4,6,3,7]

Why am I getting the wrong values?

player_list= {'peter':0, 'karel':0}
naam = input("Welke speler moet een score + 1 krijgen?")
for key, value in player_list.items():
player_list[naam] = value + 1
print(player_list)
Can someone explain me I why get the correct value whenever I enter "peter" but not when I enter "karel"?
I assume, that you'd like to increment dict value of the key which is same as the string that user provides via input. Ask yourself, do you really need to iterate over dict items to do such thing? Dict is key-value structure, and you can access value of the key whenever you provide this key directly.
>>> player_list = {'peter':0, 'karel':0}
>>> player_list['peter']
0
Setting value to the existing dict key is easy. All you need to do is:
>>> player_list['peter'] = 3
>>> player_list['peter']
3
If you'd like to increment value for 'peter' you need to take whatever is stored under 'peter' and add one, but there is no need to iterate over dict items to do that. Like with any other variable, dict element is kind of placeholder for some space of memory that you can access via that placeholder. So in case of any variable you'd do something as:
>>> x = 1
>>> x = x + 1 # or x += 1 for short
...and in case of dict element, you can do the same:
>>> player_list['peter'] = player_list['peter'] + 1 # or:
>>> player_list['peter'] += 1
If you're curious why your current code doesn't work as you expected, run your code using debugger or just add print function:
for key, value in player_list.items():
print("Current key: {}, current value: {}".format(key, value))
player_list[naam] = value + 1
In fact, it's always good to use some debugging tools whenever you don't know why your code execution is different than your expected result.

setting an array element with a list

I'd like to create a numpy array with 3 columns (not really), the last of which will be a list of variable lengths (really).
N = 2
A = numpy.empty((N, 3))
for i in range(N):
a = random.uniform(0, 1/2)
b = random.uniform(1/2, 1)
c = []
A[i,] = [a, b, c]
Over the course of execution I will then append or remove items from the lists. I used numpy.empty to initialize the array since this is supposed to give an object type, even so I'm getting the 'setting an array with a sequence error'. I know I am, that's what I want to do.
Previous questions on this topic seem to be about avoiding the error; I need to circumvent the error. The real array has 1M+ rows, otherwise I'd consider a dictionary. Ideas?
Initialize A with
A = numpy.empty((N, 3), dtype=object)
per numpy.empty docs. This is more logical than A = numpy.empty((N, 3)).astype(object) which first creates an array of floats (default data type) and only then casts it to object type.

Switching positions of two strings within a list

I have another question that I'd like input on, of course no direct answers just something to point me in the right direction!
I have a string of numbers ex. 1234567890 and I want 1 & 0 to change places (0 and 9) and for '2345' & '6789' to change places. For a final result of '0678923451'.
First things I did was convert the string into a list with:
ex. original = '1234567890'
original = list(original)
original = ['0', '1', '2' etc....]
Now, I get you need to pull the first and last out, so I assigned
x = original[0]
and
y = original[9]
So: x, y = y, x (which gets me the result I'm looking for)
But how do I input that back into the original list?
Thanks!
The fact that you 'pulled' the data from the list in variables x and y doesn't help at all, since those variables have no connection anymore with the items from the list. But why don't you swap them directly:
original[0], original[9] = original[9], original[0]
You can use the slicing operator in a similar manner to swap the inner parts of the list.
But, there is no need to create a list from the original string. Instead, you can use the slicing operator to achieve the result you want. Note that you cannot swap the string elements as you did with lists, since in Python strings are immutable. However, you can do the following:
>>> a = "1234567890"
>>> a[9] + a[5:9] + a[1:5] + a[0]
'0678923451'
>>>

python3 string to variable

I am currently trying to implement Conway's Game of Life in a Code, and therefore built a function which generates the coordinates depending of the size of the window.
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = []
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords.append ('x'+str(n)+'y'+str(i))
return coords
Yet, I would like to randomly assign values to the resulting strings, to mark them either as alive (1) or dead (0). However they only way to convert a string to a variable name known to me is via a dict and var(), but however, it is essential for the further code that the coordinates stay sorted, as I want to be able to iterate over the ordered items and put the cursor accordingly to the coordinates name. Something like:
print ('\033['+X_COORD+';'+Y_COORD+'f'+ x1y5)
if e.g. x1y5 is the corresponding value (0 or 1) of the variable
Is there a convenient method how to either do this via a dict or how to convert the name of the strings to variable names?
Or probably. If I keep one dict and one list and store the coordinate names in the list and the values in the dict?
Thank you in advance!
kyril
You use a dictionary:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = {}
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords['x'+str(n)+'y'+str(i)] = 0
return coords
You then access the value with
coords[x][y]
And change it like so:
coords[x][y] = 1
Now, of course this converting of coordinates to strings is completely pointless. Simply use a list of lists:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = [[0]*num_x for x in range(num_y)]
return coords
And I don't know why you add 1 to the coordinates either:
def coords_maker(num_x, num_y):
return [[0]*num_x for x in range(num_y)]

Resources