Python - Automatically create new variables based on other variable [duplicate] - python

This question already has answers here:
How to declare many variables?
(5 answers)
Closed 3 years ago.
I would like to do something like this:
for i in range(0, 3):
if i == 0:
name_i = "A"
elif i == 1:
name_i = "B"
else:
name_i = "C"
to have name_o = "A", name_1 = "B", name_i = "C".
I know I cannot do it like that method but is there some trick I can use to achieve that?

Dict example:
names = ['A', 'B', 'C']
my_dict = {}
for n, i in enumerate(names):
name = 'name_{}'.format(n)
my_dict[name] = i
Output:
{'name_0': 'A', 'name_1': 'B', 'name_2': 'C'}

Depending on where you get your A, B, C from, you can simply take them out of a list.
# or wherever your letters / whatever come from
import string
abc = string.ascii_uppercase
name0, name1, name2 = abc[0: 3]
print(name0)
print(name1)
print(name2)

Related

on calling a function which returns a dictionary more than once it returns empty dictionary. why is this happening and how can i fix it [duplicate]

This question already has answers here:
Why can't I iterate twice over the same iterator? How can I "reset" the iterator or reuse the data?
(5 answers)
Closed last month.
I have created 2 scripts in python : script 2 contains 3 functions one to create a dictionary second to return a dictionary and third is a random function . and script 1 contains 5 functions
fun1 is to call create dictionary function fun2 , fun3 , fun4 are random calculation function and fun5 calls and print the return dictionary function.
Script 1:
from p2 import *
def fun1(keys,values):
create_map(keys,values)
def fun2(n):
rand_fun(n)
def fun3(n):
rand_fun(n)
def fun4(n):
rand_fun(n)
def fun5(lst):
print(return_map(lst))
keys = [1,2,3]
values = ['a','b','c']
data = create_map(keys,values)
fun2(2)
fun3(3)
fun4(4)
dictionary = fun5(data)
dictionary1 = fun5(data)
dictionary2 = fun5(data)
Script 2:
def create_map(keys, values):
return zip(keys,values)
def return_map(data):
return dict(data)
def rand_fun(n):
return print((n+1)%2)
The output is:
1
0
1
{1: 'a', 2: 'b', 3: 'c'}
{}
{}
Why am i getting empty dictionary the second and third time and how can i fix this issue
reason:
zip can only use once.
reference:Python zip object 'disappears' after iterating through?
code:
keys = [1,2,3]
values = ['a','b','c']
data = create_map(keys,values)
fun2(2)
fun3(3)
fun4(4)
dictionary = fun5(create_map(keys,values))
dictionary1 = fun5(create_map(keys,values))
dictionary2 = fun5(create_map(keys,values))
result:
1
0
1
{1: 'a', 2: 'b', 3: 'c'}
{1: 'a', 2: 'b', 3: 'c'}
{1: 'a', 2: 'b', 3: 'c'}
change your create_map function to this.
def create_map(keys, values):
return dict(zip(keys,values))
like leaf_yakitori said zip can only be used once.

Differentiate output based on people names?

I'm working on this code that basically gives output based on the input (the users names) that the user give, i need help/ advice on how i can differentiate the output given based on the name.
i've tried if statements, but its really basic detecting, since i've only studied python not so long ago.
# var
import random
nopes = ("nope1", "nope2", "nope3")
list1 = 1
list2 = 2
list3 = 3
list4 = 4
list5 = 5
list6 = 6
list7 = 7
list8 = 8
list9 = 9
# functions
def mainfunc():
if a in "name1":
print(list1)
elif a in "name2":
print(list2)
elif a in "name3":
print(list3)
elif a in "name4":
print(list4)
elif a in "name5":
print(list5)
elif a in "name6":
print(list6)
elif a in "name7":
print(list7)
elif a in "name8":
print(list8)
elif a in "name9":
print(list9)
else:
talk()
def talk():
print(random.choice(nopes))
#syntax's
a = input("What's your name? : ")
mainfunc()
yes, it works. but with a single typo the code would not work as i expected, and im trying to avoid that.
I don't completely get the intention of your code, but if you want to print differnt lists based on the input, you could use a dictionary instead of the several list#-objects.
lists = {
"name1": ["a","b","c"],
"name2": ["d","e","f"]
}
a = "name1"
if (a in lists.keys()):
print(lists[a])
# Output: ['a', 'b', 'c']
That way, you just have to maintain the dictionary object and not many single objects and the elseifs

Python: Counting String frequency list type [duplicate]

This question already has answers here:
Counting occurrences without using collections.Counter
(5 answers)
Closed 5 years ago.
I am using python to count the frequency of list WITHOUT using any collection just solely my own python basics functions.
My code is:
my_list = ['a', 'b','a', 'a','b','b', 'a','a','c']
def counting():
#Please help
Print out put should be like
a: 5
b: 3
c: 1
Please help thank you.
Use count , an inbuilt list function.
def counting(my_list):
return { x:my_list.count(x) for x in my_list }
Just call it :
>>> counting(my_list)
=> {'a': 5, 'b': 3, 'c': 1}
#print it as per requirement
>>> for k,v in counting(my_list).items():
print(k,':',v)
a : 5
b : 3
c : 1
#driver value :
IN : my_list = ['a', 'b','a', 'a','b','b', 'a','a','c']
Create a dictionary to hold the results and check if the key exists increment the value, otherwise set the value of 1 (first occurrence).
my_list = ['a', 'b','a', 'a','b','b', 'a','a','c']
def counting(my_list):
counted = {}
for item in my_list:
if item in counted:
counted[item] += 1
else:
counted[item] = 1
return counted
print(counting(my_list))

count number of names in list in python [duplicate]

This question already has answers here:
How to count the frequency of the elements in an unordered list? [duplicate]
(33 answers)
Closed 5 years ago.
i have one list wich has names in it:
names = ['test','hallo','test']
uniquenames = ['test','hallo']
with set i get the uniquenames so the unique names are in a different list
but now i want to count how many names there are of each so test:2 hallo:1
i have this:
for i in range(len(uniquenames)):
countname = name.count[i]
but it gives me this error:
TypeError: 'builtin_function_or_method' object is not subscriptable
how can i fix that?
You could use a dictionary:
names = ['test','hallo','test']
countnames = {}
for name in names:
countnames[name] = countnames.get(name, 0) + 1
print(countnames) # => {'test': 2, 'hallo': 1}
If you want to make it case-insensitive, use this:
names = ['test','hallo','test', 'HaLLo', 'tESt']
countnames = {}
for name in names:
name = name.lower() # => to make 'test' and 'Test' and 'TeST'...etc the same
countnames[name] = countnames.get(name, 0) + 1
print(countnames) # => {'test': 3, 'hallo': 2}
In case you want the keys to be the counts, use an array to store the names in:
names = ['test','hallo','test','name', 'HaLLo', 'tESt','name', 'Hi', 'hi', 'Name', 'once']
temp = {}
for name in names:
name = name.lower()
temp[name] = temp.get(name, 0) + 1
countnames = {}
for name, count in temp.items():
countnames.setdefault(count, []).append(name)
print(countnames) # => {3: ['test', 'name'], 2: ['hallo', 'hi'], 1: ['once']}
Use Counter from collections:
>>> from collections import Counter
>>> Counter(names)
Counter({'test': 2, 'hallo': 1})
Also, for your example to work you should change names.count[i] for names.count(i) as count is a function.

Python: Can one create new variable names from a list of strings? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I'm new to python, so I don't know if this is possible. I'm trying to create a list of variable names from a list of strings so I can then assign values to the newly created variables.
I saw another similar question, but there was already a dict pays of keys and values.
Here's my code:
def handy(self):
a = raw_input('How many hands? ')
for i in range(int(a)):
h = "hand" + str(i+ 1)
self.list_of_hands.append(h)
# would like to create variable names from self.list_of_hands
# something like "hand1 = self.do_something(i)"
print h
print self.list_of_hands
Given some of the answers, i'm adding the following comment:
I'm going to then assign dicts to each variable. So, can I create a dictionary of dictionaries?
Why don't you just construct a dictionary using the strings as keys?
>>> class test():
def handy(self):
a = raw_input('How many hands? ')
d = { "hand" + str(i + 1) : self.do_something(i) for i in range(int(a)) }
keys = d.keys()
keys.sort()
for x in keys:
print x, '=', d[x]
def do_something(self, i):
return "something " + str(i)
>>> test().handy()
How many hands? 4
hand1 = something 0
hand2 = something 1
hand3 = something 2
hand4 = something 3
Edit: You updated the question to ask if you can store a dictionary as a value in a dictionary. Yes, you can:
>>> d = { i : { j : str(i) + str(j) for j in range(5) } for i in range(5) }
>>> d[1][2]
'12'
>>> d[4][1]
'41'
>>> d[2]
{0: '20', 1: '21', 2: '22', 3: '23', 4: '24'}
>> d[5] = { 1 : '51' }
>> d[5][1]
'51'
If you ever have multiple variables that only differ by a number at the end (hand1, hand2, etc.), you need a container.
I think a dictionary would work best:
self.hands = {}
self.hands[h] = self.do_something(i)
You can access the individual keys in the dictionary easily:
self.hands['hand1']
h = "hand" + str(i+ 1)
vars()[h] = do_something(i)
Now you can call hand1 to call do_something()

Categories