Appending a dict from another program in Python - python

I have a dictionary in program A where I want program B to add new contents into. Is this something I can accomplish? I tried googling but it was all about appending a dictionary within the same code, and I really want to be able to do it from within a different program if at all possible.
I am trying to add entries to a dictionary which contains {user : password, user2 : password2} for any new users. This is not to be registered to as only an admin should be able to add users. This is where the other program idea came into play. But I am open to any solution!

If you want to achieve this using functions, you can use the dict.update function.
def combine_dicts(x, y):
x.update(y)
return x
def get_passwords():
dict = {"a":"test", "b":"testa"}
return dict
firstDict = {"this":"is", "a":"test"}
secondDict = get_passwords()
combinedDict = combine_dicts(firstDict, secondDict)
Note: The parameter you use of dict.update() will override existing value/key pairs.

Related

Converting a QTreeWidget to a nested dictionary in PyQt

The reason I want to do this is to allow the user to create a file tree using a QTreeWidget, then I want to extract that tree in to a nested dict structure, and save it some how. I've thought about using a txt file and eval aproach to simply load all the saved schemes into some array or just another dict where the key is the name of the scheme, so the user can then simply select a scheme or edit it if they wish. This naturally leads to me having to then convert that saved dict back into a QTreeWidget after the user has selected edit.
For now though here's my problem.
I've been able to successfully navigate the QTreeWidget using a recursive a function. What I struggle with is the logic behind creating the nested dict.
Below is what i have come up with so far:
def tree_to_dict(self, parent, key):
for i in range(parent.childCount()):
cur_par = parent.child(i)
if cur_par.childCount() == 0:
try:
if type(self.scheme[key]) is dict :
self.scheme[key][cur_par.text(0)] = 'E'
except KeyError:
key = cur_par.text(0)
self.scheme[key] = 'E'
else:
key = cur_par.text(0)
self.scheme[key] = {}
self.tree_to_dict(cur_par, key)
I know this is wrong. It's why I need help.
The above code generates the following dict form the following QTreeWidget
a
b
a
c
{'a':'E', 'b':{'a':'E', 'c':'E'}}
But it should be:
{'a':'E', 'b':{'a':'E'}, 'c':'E'}
The E simply means that there will be no further subdirectories.
I've seen some other implementations of this but their horribly confusing and I don't quite get their logic. This is a near duplicate of the question I'm asking here, but it's yet to be answered. I've tried adapting his implementation but it's (to me anyway) convoluted and hard to fit into the structure of my program.
Your implementation is probably too complex than required.
Since each item is the key, you need to iterate recursively and return the values for that key.
If the item has no children, it will return 'E', otherwise will it will call the function again with the given child, and so on.
The function doesn't need the key argument, as it will be created by the recursive call.
def tree_to_dict(parent):
childCount = parent.childCount()
if not childCount:
return 'E'
content = {}
for row in range(childCount):
child = parent.child(row)
content[child.text(0)] = tree_to_dict(child)
return content
Then, just call the function using the invisibleRootItem().

Can you call/use a function returned from a list in Python?

I'm trying to store a function in a list, retrieve the function from the list later, and then call on that function. This is basically what I want to do, without any specifics. It doesn't show my purpose, but it's the same issue.
elements: list = [] # List meant to contain a tuple with the name of the item and the function of the item.
def quit_code():
exit()
element.append(("quit", quit_code))
Now, somewhere else in the code, I want to be able to use an if statement to check the name of the item and, if it's the right one at that time, run the function.
user_input = "quit" # For brevity, I'm just writing this. Let's just imagine the user actually typed this.
if elements[0][0] == user_input:
#This is the part I don't understand so I'm just going to make up some syntax.
run_method(elements[0][1])
The method run_method that I arbitrarily made is the issue. I need a way to run the method returned by elements[0][1], which is the quit_code method. I don't need an alternative solution to this example because I just made it up to display what I want to do. If I have a function or object that contains a function, how can I run that function.
(In the most simplified way I can word it) If I have object_a (for me it's a tuple) that contains str_1 and fun_b, how can I run fun_b from the object.
To expand on this a little more, the reason I can't just directly call the function is because in my program, the function gets put into the tuple via user input and is created locally and then stored in the tuple.
__list_of_stuff: list = []
def add_to_list(name, function):
__list_of_stuff.append((name, function))
And then somewhere else
def example_init_method():
def stop_code():
exit()
add_to_list("QUIT", stop_code())
Now notice that I can't access the stop_code method anywhere else in the code unless I use it through the __list_of_stuff object.
Finally, It would be nice to not have to make a function for the input. By this, I mean directly inserting code into the parameter without creating a local function like stop_code. I don't know how to do this though.
Python treats functions as first-class citizens. As such, you can do things like:
def some_function():
# do something
pass
x = some_function
x()
Since you are storing functions and binding each function with a word (key), the best approach would be a dictionary. Your example could be like this:
def quit_code():
exit()
operations = dict(quit=quit_code)
operations['quit']()
A dictionary relates a value with a key. The only rule is the key must be immutable. That means numbers, strings, tuples and other immutable objects.
To create a dictionary, you can use { and }. And to get a value by its key, use [ and ]:
my_dictionary = { 'a' : 1, 'b' : 10 }
print(my_dictionary['a']) # It will print 1
You can also create a dictionary with dict, like so:
my_dictionary = dict(a=1, b=10)
However this only works for string keys.
But considering you are using quit_code to encapsulate the exit call, why not using exit directly?
operations = dict(quit=exit)
operations['quit']()
If dictionaries aren't an option, you could still use lists and tuples:
operations = [('quit',exit)]
for key, fun in operations:
if key == 'quit':
fun()

Python - Dynamically created dictionary can't be returned or added to another dictionary

I've got a function that dynamically creates some number of dictionaries. What I'm trying to do, is to add each of those dictionaries to another dictionary, and then return that dictionary of dictionaries.
The dictionaries are all created just fine. I've stepped through the process and inspected the variables, it all looks good.
But when I try to add them to another dictionary (as a value), all that gets added is None.
I think this might have something to do with global and local variables, but I'm not sure.
This is the code that creates the dictionaries inside the function
def build_DoD(block, page, PROJECT, master_string, logging):
# other code up here
exec("{} = {{}}".format(base))
exec("{0}['section'] = '{1}'".format(base, section))
exec("{}['question_number'] = '{}'".format(base, question_number))
exec("{}['sub_question_label'] = '{}'".format(base, sub_question_label))
exec("{}['sub_question_text'] = '{}'".format(base, sub_question_text))
exec("{}['display_function'] = '{}'".format(base, display_function))
exec("{}['has_other'] = '{}'".format(base, has_other))
exec("{}['has_explain'] = '{}'".format(base, has_explain))
exec("{}['has_text_year'] = '{}'".format(base, has_text_year))
exec("{}['randomize_response'] = '{}'".format(base, randomize_response))
exec("{}['response_table'] = '{}'".format(base, resp_table))
# here is where I try to add the dynamically created dict to a larger dict.
dict_of_dicts[str(base)] = exec("{}".format(base))
OK, don't do this. Ever.
Don't use exec outside of really special cases. But to answer the question, even if I don't thing you should use it: The problem you are having is that exec does not return anything. It just executes the code, it does not evaluate it. For that, there is the function eval. Replace exec in the last line with eval.
I however fully agree with #RafaelC. This is the XYProblem

How do you include a command in a dictionary?

I'm creating a smart Chatbot. That part of information is irrelevant, however. What I'm trying to do is call on an instruction from within a dictionary - I'll show you:
dictionary = ["command1": "print("I just called command1!")]
dictionary["command1"]
Sort of like that. Obviously you cannot do that. I want to be able to have a dictionary of different commands which will run when you use dictionary[whatever_command you want_in_here]
Do you see what I mean?
I could use functions, but clearly that would take up a whole lot of space and lots of code which I cannot afford when there are so many responses in my Chatbot.
I really need to know how to do this in a simple way.
Store instructions as anonymous functions:
dictionary = {
"command1": lambda: print("I just called command1!"),
"command2": lambda: print("I just called command2!")
}
command = input('Enter command: ')
dictionary[command]()
If you're just looking to print strings, you're much better off doing something like:
dictionary = {"command1": "I just called command1!"}
print(dictionary["command1"])
but if you need to parse actual functions, you can, as #Uriel Eli said in the other answer, using a lambda.
mylist = []
dictionary = {"command1": lambda: print("I just called command1"), "command2": lambda: mylist.append("Here's an appended string!")}
dictionary["command1"]()
dictionary["command2"]()

accessing PART of a file name based on user input to a function--Python

I'm a newb trying to figure out how to accomplish the following:
I have dicts named after users in the following format:
<user>_hx
I want to access them with a function like so:
def foo(user, other_stuff):
user_hx[key]
......etc.
I attempted to access with % as follows:
def foo(user, other_stuff):
%r_hx %user[key]
but for obvious reasons I know that can't work.
Adivce?
What I think you are asking is how to access a variable based on a string representing its name. Python makes this quite easy:
globals()['%s_hx' % user]
will give you the variable <user>_hx, so you just want
globals()['%s_hx' % user][key]
(I'm not sure whether you should be using globals() or locals(); it will depend on how your variables are defined and where you are trying to access them from)
That said, there is probably an easier/cleaner way to do whatever you are doing. For instance, have you considered putting all these dictionaries in a 'master' dictionary so that you can pass them around, as well as just access them
def foo(user,other_stuff):
fname = "%s_hx"%user[key] #not sure where key is comming from... but would result in something like "bob_hx"
with open(fname) as f:
print f.read()
maybe?/
Don't use the name as a variable. You can put your collection of dictionaries inside another, top-level, dictionary with those names as keys.
users = {
"user1_hx": {"name": "User 1"},
"user2_hx": {"name": "User 2"),
}
etc.
Then access as:
realname = users["%s_hx" % name]["name"]
etc.

Categories

Resources