I am new to python and learning Dictionary. I am ended up writing the following program in which I am trying to use dictionary to resolve the argument.
Program :
def fun1(self)
options = {'abc': '123', 'edf': '456'}
args = {'op': options[self.arg]}
Now, let's assume that I am passing either 'abc' or 'edf' as argument which I am successfully storing in arg.
Now, what I want to do here is that I want to fetch value according to the key that passed as argument and want to store that value in op
So, is there any problem here in my approach? Are the dictionary tend to use this way? How to achieve this with or without Dictionary?
I use mapping dictionaries like this extensively, they are a good way to avoid mutliple if/elif/else statements.
Just be sure to catch missing keys:
args = {'op': options.get(self.arg, None)}
Or if you don't want to store anything in args:
args = {'op': options[self.arg]} if self.arg in options else None
Related
#python
sql="UPDATE bebliothequee SET title=:titl,author=:autho,ISBN=:ISB WHERE oid='{}'.format(oid.get())",title='{}'.format(title_editor.get()),author='{}'.format(author_editor.get()),ISBN='{}'.format(ISBN_editor.get()),oid='{}'.format(record_id.get())
Your first mistake is that you didn't read Stackoverflow documentation how to create good question. So you didn't add all details in question - and we can't read in your mind - and we can't help it.
Next mistake: you put code in comment but you should put it in question so it would be more readalbe but what is more important: all people could see it and help you.
Code shows that you try to create sql =... with all arguments for execute() and later use it in execute() but it doesn't work this way. You can't assing positional and named values to variable and later put it in function. You should use it directly in execute() or you should create list/tuple with positional variables and dictionary with named variables.
BTW: you don't need '{}'.format() to convert it to strings. You could use str() but I think execute() should convert it automatically.
query = "UPDATE bebliothequee SET title=:title, author=:author, ISBN=:ISBN WHERE oid=:oid"
execute(query, title=title_editor.get(), author=author_editor.get(), ISBN=ISBN_editor.get(), oid=record_id.get())
Other problem is that you use :titl but you should use full name :title like in argument title=....
You have also oid='{}'.format(oid.get() inside query which is totally useless.
BTW: Eventually you can create dictionary
args = {
'title': title_editor.get(),
'author', author_editor.get(),
'ISBN': ISBN_editor.get(),
'oid': record_id.get(),
}
and then you can use ** to unpack it as named arguments
execute(query, **args)
I am using Argh in Python 3.6 to create a complex command-line function, but because of my deep configuration file, getting a default value for an argument in the function takes a long string of dictionary keys.
This does not look particularly readable because there is a dictionary value as a key of another dictionary. It could get even more nested than
this.
There can be more arguments with default values like this, so keeping this up would get even more confusing soon. This is and example with just one default argument:
import argh
import config
#arg('-v', '--version')
def generate(
kind,
version=config.template[config.data['default']['template']]['default']['version']):
return ['RETURN.', kind, version]
The version argument default value is retrieved from my config module that generates a lot of data in list and dictionary formats.
To try and better explain the default value:
config.template[ # dictionary containing variables for a particular template
config.data['default']['template'] # the default template name set in the main configuration
]['default']['version'] # The default version variable within that particular template
What do you recommend to keep this more readable?
I'd just use the same trick used for mutable default values. This gives you more room to write something more readable.
#arg('-v', '--version')
def generate(kind, version=None):
if version is None:
d = config.data['default']['template']
version = config.template[d]['default']['version']
return ['RETURN.', kind, version]
One drawback is that this is techinically different, as the data in config.data (or any of the dicts) could change between when the function is defined and when it is run. You can do the dict lookups once before the function is defined to mitigate that.
# Choose whatever refactoring looks good to you
default_template = config.data['default']['template']
default_version = config.template[default_template]['default']['version']
#arg('-v', '--version')
def generate(kind, version=default_version):
return ['RETURN.', kind, version]
del default_template default_version # Optional
Why do it on one line:
default_template_id = config.data['default']['template']
default_template = config.template[default_template_id]
default_version = default_template['default']['version']
def generate(kind, version=default_version):
return ['RETURN.', kind, version]
I want to convert certain values of a dictionary as multiple args and pass it to a method. The key of the dict needs to be the name of the variable passed to the method.
eg:
myDict={'one':1,'two':2,'three':3,'four':4}
#call myMethod as
myMethod(one=1,two=2)
def myMeth(self,*args):
do somthing with args
You can use the unpacking notation. If you have a method like this
def function(arg1,arg2,arg3):
# do something
and a dictionary dct = {'arg1':3,'arg2':3,'arg3':6}, you can call the function like
function(**dct)
which is equivalent to doing function(arg1=3,arg2=3,arg3=6).
Notice the double stars. This means to take the dictionary and pass its values as named parameters where the keys are the names. A single star would unpack a list, passing its values in order as unnamed parameters. These can be combined.
See section 4.7.4 of the python documentation for more detail. Here is another article discussing these as well.
Use ** for passing or accepting dictionary arguments. The following code
d={'foo': 'bar','test': 123}
def my_method(**kwargs):
print kwargs
my_method(**d)
would print the contents of d, {'foo': 'bar','test': 123}
EDIT: #Matthew 's answer sums it up nicely, via the comparison of *args.
This is actually related to a previous question that I have asked about here:create multiple objects of a class with different arguments
I want to know if there is a way to send one of the objects as an argument for another when using dictionaries keys as objects.. e.g.:
objects={'obj1':['object1','Tom',10],'obj2':['object2','John',13]}
dic={name: MyClass(*args) for name, args in objects.items()}
in the normal coding I would write ....
obj1 = MyClass('object1','Tom',10)
obj2 = MyClass('object2','John',obj1)
but with the following structure, it doesn't accept passing the object obj1:
objects={'obj1':['object1','Tom',10],'obj2':['object2','John',obj1]}
dic={name: MyClass(*args) for name, args in objects.items()}
where it gives (NameError: global name 'obj1' is not defined):
so how can i do this when using dictionary keys as an objects in a right way?
updated.. error message has been added.
objects={'obj1':['object1','Tom',10],'obj2':['object2','John',obj1]} this wont work ever
however you could do something like
objects={'obj1':['object1','Tom',10],'obj2':['object2','John','obj1']}
fetch_ob = lambda x:objects.get(x,x)
dic = {name:MyClass(*list(map(fetch_ob,args))) for name,args in objects.items()}
but its kind of gross
I was looking at this code on the Google Map API website:
import simplejson, urllib
GEOCODE_BASE_URL = 'http://maps.googleapis.com/maps/api/geocode/json'
def geocode(address,sensor, **geo_args):
geo_args.update({
'address': address,
'sensor': sensor
})
url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args)
result = simplejson.load(urllib.urlopen(url))
print simplejson.dumps([s['formatted_address'] for s in result['results']], indent=2)
if __name__ == '__main__':
geocode(address="San+Francisco",sensor="false")
I noticed that in the geocode function, when we actually apply the function we don't use the geo_args dictionary when we call the function, but we instead use it to initialize a dictionary we update in the next lines. What is the benefit of using this, as opposed to initializing the dictionary within the function itself? It makes the code a bit less clear so I assume there is a reason for doing it.
geo_args is used. The literal dictionary
{
'address': address,
'sensor': sensor
}
updates geo_args, not the other way around.
The reason it's like this looks to me that address and sensor are required arguments. This structure allows the function to enforce that requireness, and also allow them to be passed positionally. The .update() is just there to consolidate all the arguments into one so they can be given to urllib.urlencode.
Not clear? This is the normal behaviour of **kwargs (the keyword argument dictionary).
So when you see something with **, a bunch of named parameters or keyword arguments will be passed.
Seeing the other answers. I probably misunderstood your question. I agree with the other answers: address and sensor are required.