we could open a dictionary with **:
dict = {"v_1":"a","v_2":"b"}
function(**dict) >
function(v_1 = "a",v_2 = "b")
So is it possible to open dictionaries to represent bool expressions so:
dict = {"v_1":"a","v_2":"b"}
function(???) >
function(v_1 == "a",v_2 == "b")
where i want to use this process:
https://docs.sqlalchemy.org/en/14/core/tutorial.html#inserts-updates-and-deletes
in this code as an example:
tmt = users.update().where(users.c.name == 'jack').values(name='ed')
on where function .where(users.c.name == 'jack').
I also have a dictionary:
{"name":"jack"}
Is there any way I can pass this dictionary to the function as desired?
Check **kwargs structure. You can see an example below.
def function(*args,**kwargs):
for i in args:
print(i)
for k,v in kwargs.items():
print('key: ',k,'value: ',v)
function(1,2,3,'args' , val = 'kwargs')
output
#1
#2
#3
#args
#key: val value: kwargs
What I did not understand when asking the question is that the operator == is not a bool value! was used as an object constructor. so v_1 == "a" was creating an object with v1. I've done this by scrolling through a list for now. Although it's not exactly the answer I wanted, my solution is:
dict = {"v_1":"a","v_2":"b"}
list = []
for i in dict:
list.append(i == dict[i])
function(*l)
Related
This question already has answers here:
How to check if a dictionary is empty?
(9 answers)
Closed 1 year ago.
in python:
dic = {} #start with an empty list
After this line, I did a series of command to add things to the dic. But there is also a situation where nothing is added. Then, I need to use the value in the dic.
a = min(dic, key=dic.get)
if there is nothing in the dic, it will give me an error:
ValueError: min() arg is an empty sequence I don't need an output for a if dic is empty, so I then attempted to use the if statement to get away:
if dic == None:
pass
else:
a = min(dic, key=dic.get)
but this will still give me the same error. Is there a way to skip this line of codea = min(dic, key=dic.get)when dic = {}?
The dic is of the <class dict> whereas the None object is of the <class 'Nonetype'>.
So the given expression dic == Nonewill always return False.
Instead change it to dic == {} or len(dic) == 0 or simply dic.
An empty dictionary will usually evaluate to False.
if dic:
pass
else:
a = min(dic, key=dic.get)
Try changing the logic to:
if len(dic) == 0:
pass
else:
a = min(dic, key=dic.get)
You current code skips over the pass block because even if the dict dic is empty, it is not None, there's a bunch of ways to check emptiness of a dict, personally, I'm a fan of checking the len as above but there are other way such as on this page.
I recently received an answer from the stackoverflow fellow on my previous question and I tried to inquire more in order to understand the function but somehow no response so I wish to ask it here.
I wanted to know what is the k and v that used in the lambda represent? I thought it was representing like this......
k = dictionary ?
v = string ? # Did I understand it correctly?
dictionary = {"test":"1", "card":"2"}
string = "There istest at the cardboards"
from functools import reduce
res = reduce(lambda k, v: k.replace(v, dictionary[v]), dictionary, string)
since we use lambda then it loop each of the element within both of these variables. But why k.replace? Isnt that a dictionary? Should It be v.replace? Somehow this method works. I wish someone could explain to me how this work and please more details if possible. Thank you!
reduce is equivalent to repeatedly calling a function.
The function in this case is a lambda, but a lambda is just an anonymous function:
def f(k, v):
return k.replace(v, dictionary[v])
The definition of reduce itself is (almost—the None default here is not quite right, nor the len test):
def reduce(func, seq, initial=None):
if initial is not None:
ret = initial
for i in seq:
ret = func(ret, i)
return ret
# initial not supplied, so sequence must be non-empty
if len(seq) == 0:
raise TypeError("reduce() of empty sequence with no initial value")
first = True
for i in seq:
if first:
ret = i
first = False
else:
ret = func(ret, i)
return ret
So, ask yourself what this would do when called on your lambda function. The:
for i in dictionary
loop will iterate over each key in the dictionary. It will pass that key, along with the stored ret (or the initial argument for the first call), to your function. So you'll get each key, plus the string value that's initially "There istest at the cardboards", as your v (key from dictionary, called i in the expansion of reduce) and k (long string, called ret in the expansion of reduce) arguments.
Note that k is the full text string, not the string used as the key in the dictionary, while v is the word that is the key in the dictionary. I've used the variable names k and v here only because you did too. As noted in a comment, text and word might be better variable names in either the expanded def f(...) or the original lambda function.
Trace your code execution
Try the same code, except that instead of just:
def f(k, v):
return k.replace(v, dictionary[v])
you write it as:
def f(text, word):
print("f(text={!r}, word={!r})".format(text, word))
replacement = dictionary[word]
print(" I will now replace {!r} with {!r}".format(word, replacement))
result = text.replace(word, replacement)
print(" I got: {!r}".format(result))
return result
Run the functools.reduce function over function f with dictionary and string as the other two arguments and observe the output.
(So I have a group of levels for a game, lets just say level1 - level10.
I have a function called level_up() and inside I have a dictionary that is used to group "level name" as a key to be stored in a json file and used later, and a value that is the function to be called.
So what this looks like is:
levels = {
"level1":level1 #level1 is the function to be executed
"level2":level2
}
all the way down to the tenth level.
I would try to call the function like so:
a = list(sorted(levels.keys())) # to sort the keys in order
b=level.values()
list(sorted(b))
b = b.pop(0)
b()
This of course results in an error
TypeError: '<' not supported between instances of 'function' and 'function'
I guess it would be easier to just make two lists but for learning purposes would like to see if I could make this function nice and concise so feel free to give any advice.
Why use strings as keys? Simpler, no need to sort:
import sys
def level1(): print(1)
def level2(): print(2)
def level3(): print(3)
def win():
print("you won")
sys.exit()
curr_lvl = 1 # start here and advance
levels = { 1:level1, 2:level2, 3:level3}
while True:
levels.get(curr_lvl,win)() # get func and call it
curr_lvl += 1
Output:
1
2
3
you won
If you really nead a "string" key - process it:
def get_level(s):
levels = { 1:level1, 2:level2, 3:level3, 4:level4, 5:level5}
try:
lvl = int(s.lstrip("level"))
except ValueError:
pass
return levels.get(lvl,win)
get_level("level2")() # prints 2
There is no such thing as a "sorted dictionary". Let that be clear.
Here is a possible answer, I am sure there is a more beautiful way:
map(lambda i: i[1], sorted(levels.items(), key=lambda i: i[0]))
How can I detect some missing key on location.raw["address"] dictionary. This because, some address doesn't have ['city'] or ['road'] key :(
It gives difficult to me to save the data in the dataframe Python.
This is my code:
from geopy.geocoders import Nominatim
r=[]
h=[] #empty list
c=[]
for i in df['coordinates']:
loc=geolocator.reverse("%s"%i,timeout=120)
print(loc)
if loc.raw["address"]["road"] == None: #i tried use this way, not works
r.append(" ")
print("masuk 1")
else:
road=loc.raw["address"]["road"]
r.append(road)
print("masuk 2")
ham=loc.raw["address"]
name=loc.raw["display_name"]
h.append(ham)
c.append(name)
df = pd.DataFrame({'text':text,'city':c,'neighbourhood':h})
You could use in keyword to check if key presented in dict:
a = {1:2, 'x': [3,4]}
print(1 in a) # True
print(2 in a) # False
print('x' in a) # True
Also, dict objects has get method, which returns some value if key is absent:
a.get(1) # 2
a.get(2) # None -- default value
a.get(2, 'n/a') # 'n/a'
I have the following dictionary containing a bunch of functions and their keys as in the bellow example:
function_list = {0:power_off(), 1:image_capture(100,1000,100,100), 2:video_record(100,100), 3:image_settings(), 4:video_settings(), 5:device_settings()}
Actually there are about 5 times more, but I simplified it for this post...
My question is, how should I proceed so that when I define the function_list dictionary, it will not run all the functions from it's content, rather just at when I call them in the following manner: function_list[current_selection], based on the value of current_selection parameter.
I'm doing this so I don't have to have a long and complex if... elif statement like:
if current_selection == 0:
power_off()
elif current_selection == 1:
image_capture(100,1000,100,100)
elif current_selection ==2:
video_record(100,100)
... and so on ...
If anyone could help me out, I would really appreciate it.
Thanks!
Try this :
function_list = {0:{"func":power_off},
1:{"func":image_capture, "args":(100,1000,100,100)},
2:{"func":video_record, "args":(100,100)},
3:{"func":image_settings},
4:{"func":video_settings},
5:{"func":device_settings} }
f = function_list[current_selection]
if "args" in f:
f["func"](*f["args"])
else:
f["func"]()
The problem is you are making function calls. The values in the dictionary should be function references.
function_list = {0:power_off}
and then to call,
function_list[0]().
If you have to pass arguments, you can replace the function reference with a lambda expression.
function_list = {1: lambda arg1, arg2: image_capture(arg1, arg2)}