Can i put anything in for x - python

I am learning how to code in python so I'm wondering if we can put anything in for x (key in this instance):
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]

Yes, you can put any name there that you wish -- just as long as it's a valid variable name in Python. key is going to be the variable name for each item inside the for block.

Related

What does this python codes mean?

What does this python codes mean? New to python. THX!
benchmark_sets_list = [
'%s: %s' %
(set_name, benchmark_sets.BENCHMARK_SETS[set_name]['message'])
for set_name in benchmark_sets.BENCHMARK_SETS]
This part...
for set_name in benchmark_sets.BENCHMARK_SETS
...will grab the set names from benchmark_sets.BENCHMARK_SETS and it will keep them one by one into a set_name variable.
After that, it will be able to know the values from this line...
(set_name, benchmark_sets.BENCHMARK_SETS[set_name]['message'])
...because set_name will have a value. That part will return two things, set_name and benchmark_sets.BENCHMARK_SETS[set_name]['message']. Probably those two things will be both strings.
Then, those %s you see in this line...
'%s: %s' %
...will be replaced by the value of set_name and benchmark_sets.BENCHMARK_SETS[set_name]['message'] respectively. That will generate an string like this one: "foo: bar", being "foo" the value of set_name and "bar" the value of benchmark_sets.BENCHMARK_SETS[set_name]['message'].
In order for you to understand what happened there, this is a simple example:
"%s %s %s" % (first_elem, second_elem, third_elem)
That code will replace the first %s with the value of first_elem The second %s with the value of second_elem, and the third %s with the value of third_elem.
And finally that string will be added to the list which is being constructed. So, at the end you will have an list more or less like this one:
["foo: bar", "wop: wap", "bing: bang"]

Learn Python The Hard Way - Exercise 39

On Exercise 39 of Learn Python The Hard Way, lines 37 to 39 look like this:
print "-"*10
for state, abbrev in states.items():
print "%s has the city %s" % (state, abbrev)
I thought I understood this. I thought Python was taking the KEY:VALUE from "states" and assigning the KEY to "state" and the VALUE to "abbrev".
However, I found something strange happened when I entered the following code:
print "-"*10
for test in states.items():
print "%s has the city %s" % (test)
It produces the same output as the original code.
But, it only works if you put the %s into the print statement twice.
Can someone explain what is happening with "test"?
What exactly is "test"? Is it a Tuple?
It seems to contain both the KEY and the VALUE from states.items().
I have looked through some of the other questions on Exercise 39 here and I haven't found the same query.
The code is listed below (for Python 2.7)
# create a mapping of state to abbreviation
states = {
'Oregan': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York' : 'NY',
'Michigan' : 'MI'
}
print "-"*10
for state, abbrev in states.items():
print "%s has the city %s" % (state, abbrev)
print "-"*10
for test in states.items():
print "%s has the city %s" % (test)
states is a dictionary, so when you called for test in states.items() it assigns each item of the dictionary (a tuple) to test.
Then you are just iterating over the items and printing their keys and values as you would with for state, abbrev in states.items():
>>> for state in states.items():
print (state) # print all the tuples
('California', 'CA')
('Oregan', 'OR')
('Florida', 'FL')
('Michigan', 'MI')
('New York', 'NY')
All the details are available online, for instance in PEP 234 -- Iterators under Dictionary Iterators:
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write
for k in dict: ...
which is equivalent to, but much faster than
for k in dict.keys(): ...
as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
Add methods to dictionaries that return different kinds of iterators explicitly:
for key in dict.iterkeys(): ...
for value in dict.itervalues(): ...
for key, value in dict.iteritems(): ...
This means that for x in dict is shorthand for for x in
dict.iterkeys().
This "missing link" between your first and second code snippet explains why they are equivalent:
print "-"*10
for test in states.items():
state, abbrev = test
print "%s has the city %s" % (state, abbrev)

Iterate through dictionary values?

Hey everyone I'm trying to write a program in Python that acts as a quiz game. I made a dictionary at the beginning of the program that contains the values the user will be quizzed on. Its set up like so:
PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}
So I defined a function that uses a for loop to iterate through the dictionary keys and asks for input from the user, and compares the user input to the value matched with the key.
for key in PIX0:
NUM = input("What is the Resolution of %s?" % key)
if NUM == PIX0[key]:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: %s." % PIX0[key] )
This is working fine output looks like this:
What is the Resolution of Full HD? 1920x1080
Nice Job!
What is the Resolution of VGA? 640x480
Nice Job!
So what I would like to be able to do is have a separate function that asks the question the other way, providing the user with the resolution numbers and having the user enter the name of the display standard. So I want to make a for loop but I don't really know how to (or if you even can) iterate over the values in the dictionary and ask the user to input the keys.
I'd like to have output that looks something like this:
Which standard has a resolution of 1920x1080? Full HD
Nice Job!
What standard has a resolution of 640x480? VGA
Nice Job!
I've tried playing with for value in PIX0.values() and thats allowed me to iterate through the dictionary values, but I don't know how to use that to "check" the user answers against the dictionary keys. If anyone could help it would be appreciated.
EDIT: Sorry I'm using Python3.
Depending on your version:
Python 2.x:
for key, val in PIX0.iteritems():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
Python 3.x:
for key, val in PIX0.items():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
You should also get in the habit of using the new string formatting syntax ({} instead of % operator) from PEP 3101:
https://www.python.org/dev/peps/pep-3101/
You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items(). Then you have both directly in variables and don't need a lookup at all:
for key, value in PIX0.items():
NUM = input("What is the Resolution of %s?" % key)
if NUM == value:
You can of course use that both ways then.
Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.
You can just look for the value that corresponds with the key and then check if the input is equal to the key.
for key in PIX0:
NUM = input("Which standard has a resolution of %s " % PIX0[key])
if NUM == key:
Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.
print("I'm sorry but thats wrong. The correct answer was: %s." % key )
Also, I would recommend using str.format for string formatting instead of the % syntax.
Your full code should look like this (after adding in string formatting)
PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}
for key in PIX0:
NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))
If all your values are unique, you can make a reverse dictionary:
PIXO_reverse = {v: k for k, v in PIX0.items()}
Result:
>>> PIXO_reverse
{'320x240': 'QVGA', '640x480': 'VGA', '800x600': 'SVGA'}
Now you can use the same logic as before.
Create the opposite dictionary:
PIX1 = {}
for key in PIX0.keys():
PIX1[PIX0.get(key)] = key
Then run the same code on this dictionary instead (using PIX1 instead of PIX0).
BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input instead of input.

Output formatting in Python: replacing %s with the defined variable

How do I replace %s with a defined/non-empty variable string? Or rather what is the Pythonic or syntactic sugar for doing so?
Example:
# Replace %s with the value if defined by either vehicle.get('car') or vehicle.get('truck')
# Assumes only one of these values can be empty at any given time
# The get function operates like http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get
logging.error("Found duplicate entry with %s", vehicle.get('car') or vehicle.get('truck'))
I think you want this:
'Found duplicate entry with %s' % (vehicle.get('car') or vehicle.get('truck'))
This will replace the '%s' with the non-empty string (assuming only one is non-empty). If both contain text, it will be replaced with the output of vehicle.get('car')
You could also use this type of string formatting:
'Found duplicate entry with {0}'.format(vehicle.get('car') or vehicle.get('truck'))
This will return the same result.
Have you tried something like this?
logging.error("Found duplicate entry with %s" % (vehicle.get('car') or vehicle.get('truck')))
Or if truck is also empty, you can return a default value:
logging.error("Found duplicate entry with %s" % (vehicle.get('car') or vehicle.get('truck', 'default')))

Accessing a variable's name [duplicate]

This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 4 months ago.
I'm trying to access a variable's name. For example, if I call a function to print a list (printL)
and want to print my list's name "A_minus_B":
def printL (xlist):
print "****************************"
print "name of list"
print (" entries : "),len(xlist)
print xlist
print "****************************"
return()
How can I get the function to print "A_minus_B" instead of "name of list", the name I used when calling the function printL(A_minus_B)?
You can't.* The detailed reasons are discussed in the Python language reference, but basically what Python does when you call printL(A_minus_B) is take the value that has been labeled A_minus_B and create a new label, xlist, that happens to refer to the same thing. From that point on, the label xlist has absolutely no connection to the other label A_minus_B, and in fact, the value which has been labeled A_minus_B or xlist or whatever has no connection to any of the names that have been used to label it.
*Well, you can, by using some deep "Python voodoo"... you would basically have to tell Python to read the piece of source code where you call printL(A_minus_B) and extract the variable name from there. Normally that's the kind of thing you probably shouldn't be doing (not because you're a beginner, but because it usually indicates you've designed your program the wrong way), but debugging is one of those cases where it's probably appropriate. Here's one way to do it:
import inspect, pprint
def print_values(*names):
caller = inspect.stack()[1][0]
for name in names:
if name in caller.f_locals:
value = caller.f_locals[name]
elif name in caller.f_globals:
value = caller.f_globals[name]
else:
print 'no such variable: ' + name
# do whatever you want with name and value, for example:
print "****************************"
print name
print (" entries : "),len(value)
print value
print "****************************"
The catch is that when you call this function, you have to pass it the name of the variable you want printed, not the variable itself. So you would call print_values('A_minus_B'), not print_values(A_minus_B). You can pass multiple names to have them all printed out, for example print_values('A_minus_B', 'C_minus_D', 'foo').
Alternate way to do it:
list_dict = {} #creates empty dictionary
list_dict['list_a'] = [1,2,3,4,5,6] # here you create the name (key)
nice_name = 'list_b'
list_dict[nice_name] = [7,8,9,10,11,12] # here you use already existing string as name (key)
def list_info(ld):
for key in sorted(ld):
print "****************************"
print key
print " entries : " ,len(ld[key])
print ld[key]
print "****************************"
list_info(list_dict)

Categories