Call multiple dictionaries who names involve i in a loop? [duplicate] - python

This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 8 months ago.
I would like to call multiple dictionaries using a for loop. I am unsure how to call multiple dictionaries properly, and I can't figure out if its possible using concatenation. The code below should explain my thinking even though the print statement is incorrect.
stat0 = {}
stat0["bob"] = 0
stat1 = {}
stat1["bob"] = 0
stat2 = {}
stat2["bob"] = 0
for i in range(3):
print(stat(i))

How about putting them in a collection, and then getting value generically:
for hm in [stat0, stat1, stat2]
print(hm["bob"])

Instead of naming your dictionaries, just put them into another dictionary:
#UNTESTED
stat = { 0: stat0, 1: stat1, 2: stat2 }
for i in range(3):
print(stat[i])
Or, use an iterative style more appropriate for dict:
#UNTESTED
for i, d in stat.items():
print(i, d)

Related

python replace() function is not working as supposed [duplicate]

This question already has answers here:
replace characters not working in python [duplicate]
(3 answers)
Closed 6 months ago.
res = "heeellooo"
D = {"aaa":"a","eee":"e","iii":"i","ooo":"o","uuu":"u","yyy":"y"}
for i,j in D.items():
res.replace(i,j)
print(res)
the output expected is:
hello
what I got instead is heeellooo
any idea why this is happening??
In the for loop you have to mention that certain content of variable "res" needs to be replaced with the certain content from the variable "D".
So, you have to change that line of code to this:
res = res.replace(i,j)
Classical problem:
res = "heeellooo"
D = {"aaa":"a","eee":"e","iii":"i","ooo":"o","uuu":"u","yyy":"y"}
for i,j in D.items():
res=res.replace(i,j)
print(res)
res = "heeellooo"
D = {"aaa":"a","eee":"e","iii":"i","ooo":"o","uuu":"u","yyy":"y"}
for i,j in D.items():
res = res.replace(i,j) # use the returned value of `replace()`
print(res)

How to sort list that i get from os.listdir(path) [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 1 year ago.
a = [
'suit1.png',
'suit10.png',
'suit2.png',
'suit12.png',
'suit3.png',
'suit4.png',
'suit5.png',
'suit6.png',
'suit7.png',
'suit8.png',
]
sorted(a), sorts items in same way as seen in a list
a.sort() also sort list in that way. Is it possible that 'suit10.png' and 'suit12.png' go on the end of list?
Use custom sort as follows:
from functools import cmp_to_key
def cmp_items(a, b):
if int(a.split('suit')[1].split('.png')[0]) > int(b.split('suit')[1].split('.png')[0]):
return 1
elif int(a.split('suit')[1].split('.png')[0]) == int(b.split('suit')[1].split('.png')[0]):
return 0
else:
return -1
cmp_key = cmp_to_key(cmp_items)
a = [
'suit1.png',
'suit10.png',
'suit2.png',
'suit12.png',
'suit3.png',
'suit4.png',
'suit5.png',
'suit6.png',
'suit7.png',
'suit8.png',
]
a.sort(key = cmp_key)
print(a)
Both the sorted function and the list.sort method take an optional key argument which dictates how items are to be sorted. Its value is to be a function that takes a member of the list as an argument and returns a value (usually a number). If a and b are elements of the list, then a will be placed before b if func(a) < func(b).
So, in this case, you could do
a.sort(key=lambda x : int(x[4:].split('.')[0]))

Is there a way to "stack" a list in python? [duplicate]

This question already has answers here:
How do I count the occurrences of a list item?
(30 answers)
Closed 3 years ago.
I am working on a project, and an annoying thing is that when I print a list e.g.('a','a','a','b','c','b'), it will print:
a a a b c b
But, I would like it to join repeat values, e.g.:
a(3) b(2) c
I have a complicated function for doing this that still does not work(shown below) and does anyone have any suggestions?
def refine(testlist):
repeatfntest=0
prototypelist=testlist.copy()
lengthtest=len(testlist)-1
testlist.sort()
repititionfn=1
occurences=0
currentterm=prototypelist[lengthtest]
finalizedtermsfn=[]
while lengthtest>-1:
repititionfn=1
lengthtest=len(prototypelist)-1
occurences=0
while repititionfn>0:
lengthtest-=1
occurences+=1
print(currentterm)
prototypelist.remove(testlist[lengthtest])
if currentterm in prototypelist:
repititionfn=1
else:
repititionfn=0
if repititionfn==0 and occurences>1:
try:
finalizedtermsfn.append(str(currentterm)+"("+str(occurences)+")")
repititionfn=1
occurences=0
currentterm=prototypelist[lengthtest]
except:
print("Fail")
del finalizedtermsfn[-1]
elif repititionfn==0 and occurences==1:
try:
finalizedtermsfn.append(str(prototypelist[lengthtest]))
repititionfn=1
occurences=0
currentterm=prototypelist[lengthtest]
except:
print("Fail")
else:
currentterm=prototypelist[lengthtest]
return(finalizedtermsfn)
a=[6,0,1,1,1,1,1,2,2,2,2,4,4,4,5,5]
print(refine(a))
This Prints:
['5(2)','4(3)','2(4)','1(5)','6']
You can use collections.Counter with a list comprehension:
a=[6,0,1,1,1,1,1,2,2,2,2,4,4,4,5,5]
from collections import Counter
print(["%s(%d)"%(k,v) for k, v in Counter(a).items()])
#['0(1)', '1(5)', '2(4)', '4(3)', '5(2)', '6(1)']
If you want to avoid printing the 1 in parentheses for the single items, you can do:
print(["%s(%d)"%(k,v) if v > 1 else str(k) for k, v in Counter(a).items()])
#['0', '1(5)', '2(4)', '4(3)', '5(2)', '6']

Python multiple elif alternatives [duplicate]

This question already has answers here:
What is the Python equivalent for a case/switch statement? [duplicate]
(2 answers)
Closed 4 years ago.
I have a script which needs to iterate through thousands of various different, but simple options.
I can use if...elif to iterate through them, but am wondering if there is a faster / better option than thousands of elifs. For example
if something == 'a':
do_something_a
elif something == 'b':
do_something_b
elif something == 'c':
do_something_c
elif something == 'd':
do_something_d
...
A thousand more elifs
...
else:
do_something_else
The thing I will be doing will usually be running a function of some kind.
you can use a dictionary to control mutliple possible logical paths:
def follow_process_a():
print('following a')
def follow_process_b():
print('following b')
keyword_function_mapper =
{'a' : follow_process_a ,
'b' : follow_process_b,
}
current_keyword = 'a'
run_method = keyword_function_mapper[current_keyword]
run_method()
you can use a dictionary for that in this way:
def do_something_a():
print 1
def do_something_b():
print 2
dict = {'a': do_something_a, 'b': do_something_b}
dict.get(something)()
What I would recommend is to create a dictionary which maps the somethings to their respective function. Then you can apply this dictionary to the data.
More information: https://jaxenter.com/implement-switch-case-statement-python-138315.html
(Dictionary Mapping)

Recursively create a nested dictionary from string [duplicate]

This question already has answers here:
Converting list to nested dictionary
(4 answers)
Closed 5 years ago.
I have an issue that I've been trying to sort out. I have a string that needs to be converted to an nested dictionary with the keys and values based off the adjacent words in the string. Here is an example:
graphMaster = {}
inputSentence = "I have a dog named Max."
I would like to take this string, and convert it into a dictionary resembling the output below:
print graphMaster
{'I': {'have': {'a': {'dog': {'named': 'Max'}}}}}
I have tried the following:
graphMaster = {}
inputSentence = "I have a dog named Max."
while True:
inputList = inputSentence.strip().split(' ')
for currentIndex, word in enumerate(inputList):
nextIndex = currentIndex + 1
if nextIndex < len(inputList):
if word not in graphMaster.keys():
graphMaster[word] = inputList[nextIndex]
elif word in graphMaster.keys():
break
print graphMaster
I couldn't find a duplicate problem here and I pre-apologize if one exists that I couldn't find. Any help is greatly appreciated.
You could do something like this:
outdict = {}
curdict = outdict
for f in inputSentence.split(' '):
curdict[f] = {}
curdict = curdict[f]
print outdict
Where curdict is only pointing to a location in the output dictionary.

Categories