How to add items to a dictionary between two methods? - python

I'm writing a method that takes in a list and returns a dictionary. This method is to be saved in a separate Python file and imported into Main.py
The method that takes in a list calls another method that's meant to update the global dictionary.
global myDict
def addKeyValuePair(listItem):
try:
key = listItem.split(': ')[0].replace('\\','')
value = listItem.split(': ')[1].replace('\\r\\n','').replace('\\','')
myDict.update({key:value})
except:
pass
def makeDict(dataList):
myDict = {}
for listItem in dataList:
addKeyValuePair(listItem)
return(myDict)
From the main method I'm importing the makeDict module and passing it the dataList, but it returns an empty dictionary.
from Toolkit import makeDict
finalDict = makeDict(dataList)
Any idea how this can be done?

Related

How to pytest local variable like dict inside function?

For example I have a function like below:
def func(val):
dict = {}
# some logic to fill in dict
dict['a'] = val
Then how can I pytest the the contents of dict? Is it possible?
You can actually replace the dict constructor, for the tested module, if you can change your code slightly. Suppose that your module name is my_module.py and you can make the following changes:
Initialize the dictionary using dict() instead of {}
Rename dict into my_dict (or any other name so it doesn't shadows the builtin dict())
my_module.py would look like so:
def func(val):
my_dict = dict() # instead of dict = {}
# some logic to fill in dict
my_dict['a'] = val
Then, in your test, override the dict constructor which creates new dictionaries and return your dictionary that you can assert later on:
from my_module import func
def test_func(mocker):
my_replaced_dict = {}
mocker.patch("my_module.dict", return_value=my_replaced_dict)
func(20)
assert my_replaced_dict['a'] == 20 # the assert works since func uses our variable

Create a dictionary with all functions from a file

Say I have a file functions.py containing
def some_function():
return "something"
def some_other_function():
return "something else"
I'm trying to create a dictionary in another file, load_functions.py, with keys being the function-names from functions.py and the items being the actual function e.g:
import functions
useable_functions = [f for f in dir(functions) if "__" not in f] #Get all functions to be used
function_dict = TO_BE_IMPLEMENTED
print(function_dict)
#{"some_function":some_function,
#"some_other_function":some_other_function}
func = function_dict["some_function"]
func()
# "something"
Is it by all means doable?
Take a look at the inspect module.
Say you have your functions.py module.
To get all functions from it, use this:
import inspect
import functions # your module
elements = inspect.getmembers(functions, inspect.isfunction)
element_dict = dict(elements)
The call will return all the function members of the functions.py module as a list of (name, value) pairs sorted by name. Note it will also include lambdas.
Then, I use dict() to convert the (name, value) pairs to a dict.
https://docs.python.org/3/library/inspect.html

Call many python functions from a module by looping through a list of function names and making them variables

I have three similar functions in tld_list.py. I am working out of mainBase.py file.
I am trying to create a variable string which will call the appropriate function by looping through the list of all functions. My code reads from a list of function names, iterates through the list and running the function on each iteration. Each function returns 10 pieces of information from separate websites
I have tried 2 variations annotated as Option A and Option B below
# This is mainBase.py
import tld_list # I use this in conjunction with Option A
from tld_list import * # I use this with Option B
functionList = ["functionA", "functionB", "functionC"]
tldIterator = 0
while tldIterator < len(functionList):
# This will determine which function is called first
# In the first case, the function is functionA
currentFunction = str(functionList[tldIterator])
Option A
currentFunction = "tld_list." + currentFunction
websiteName = currentFunction(x, y)
print(websiteName[1]
print(websiteName[2]
...
print(websiteName[10]
Option B
websiteName = currentFunction(x, y)
print(websiteName[1]
print(websiteName[2]
...
print(websiteName[10]
Even though it is not seen, I continue to loop through the iteration by ending each loop with tldIterator += 1
Both options fail for the same reason stating TypeError: 'str' object is not callable
I am wondering what I am doing wrong, or if it is even possible to call a function in a loop with a variable
You have the function names but what you really want are the function objects bound to those names in tld_list. Since function names are attributes of the module, getattr does the job. Also, it seems like list iteration rather than keeping track of your own tldIterator index would suffice.
import tld_list
function_names = ["functionA", "functionB", "functionC"]
functions = [getattr(tld_list, name) for name in function_names]
for fctn in functions:
website_name = fctn(x,y)
You can create a dictionary to provide a name to function conversion:
def funcA(...): pass
def funcB(...): pass
def funcC(...): pass
func_find = {"Huey": funcA, "Dewey": funcB, "Louie": FuncC}
Then you can call them, e.g.
result = func_find["Huey"](...)
You should avoid this type of code. Try using if's, or references instead. But you can try:
websiteName = exec('{}(x, y)'.format(currentFunction))

Python dictionary set all values to class object

After having created a dictionary from one dataframe column as keys, I want to set all values to an instance of an object (the class serves as container for storing key statistics for each row of the original pandas dataframe).
Hence, I tried this:
class Bond:
def __init__(self):
self.totalsize = 0
self.count = 0
if __name__ == '__main__':
isin_dict = list_of_isins.set_index('isin').T.to_dict()
isin_dict = dict.fromkeys(isin_dict, Bond())
The problem is that all values in isin_dict point to the same address, ie all rows share the same Bond class object.
How could I create a dictionary with each key holding a separate class instance as value?
The reason for this is already explained here
dict.fromKeys() uses the same value for every key.
The solution is to use dictionary comprehensions or to use defaultdict from collections module.
Sample Code to use defaultdict
from collections import defaultdict
class Bond:
def __init__(self):
pass
# I have just used your variable and stored in a list
d = defaultdict(lambda : list(list_of_isins.set_index('isin').T)
for keys in d:
d[keys] = Bond()
print (d)
The reason we are passing the type dict to defaultdict is the first argument should be callable for defaultdict. Else you may get a TypeError
Alternately you may also pass a lambda expression which will make it callable

need a dictionary from another function

If I have a dictionary from another function, how can I pass the dictionary within a new function?
Eg.
From another function, I have tuples like this ('falseName', 'realName', positionOfMistake), eg. ('Milter', 'Miller', 4). I have a function that make a dictionary like this:
D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...},
realName:{falseName:[positionOfMistake]...}...}
def addNameToDictionary(d, tup):
if not d.has_key(tup[0]):
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]
Now I need to write a function that takes a list of falseName's and return:
realName:
falseName
falseName
realName:...
My problem is how to call the dictionary from the function addNameToDictionary, to a new function?
I have tried the following:
def Names(nameList):
D=addNameToDictionary(d, tup)
print D
But I get:
NameError: global name 'd' is not defined
Anyone?
def your_new_function(d, falseNames):
# ... get data from d
return {realname:(falseName1, falseName2)}

Categories

Resources