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'
Answer from verdesmarald on Stack OverflowWhy 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'
h = "hand" + str(i+ 1)
vars()[h] = do_something(i)
Now you can call hand1 to call do_something()
In python create a list with a variable in the name - Stack Overflow
How to create a List given a variable "x" in Python? - Stack Overflow
List variable name involves different variable outputs
python - How can I create new variables in a loop, with the names and values coming from a list? - Stack Overflow
This is a bad idea. You should not dynamically create variable names, use a dictionary instead:
Copyvariables = {}
for name, colour, shape in Applist:
variables[name + "_n"] = name
variables[name + "_c"] = colour
variables[name + "_s"] = shape
Now access them as variables["Apple_n"], etc.
What you really want though, is perhaps a dict of dicts:
Copyvariables = {}
for name, colour, shape in Applist:
variables[name] = {"name": name, "colour": colour, "shape": shape}
print "Apple shape: " + variables["Apple"]["shape"]
Or, perhaps even better, a namedtuple:
Copyfrom collections import namedtuple
variables = {}
Fruit = namedtuple("Fruit", ["name", "colour", "shape"])
for args in Applist:
fruit = Fruit(*args)
variables[fruit.name] = fruit
print "Apple shape: " + variables["Apple"].shape
You can't change the variables of each Fruit if you use a namedtuple though (i.e. no setting variables["Apple"].colour to "green"), so it is perhaps not a good solution, depending on the intended usage. If you like the namedtuple solution but want to change the variables, you can make it a full-blown Fruit class instead, which can be used as a drop-in replacement for the namedtuple Fruit in the above code.
Copyclass Fruit(object):
def __init__(self, name, colour, shape):
self.name = name
self.colour = colour
self.shape = shape
It would be easiest to do this with a dictionary:
Copyapp_list = [
['Apple', 'red', 'circle'],
['Banana', 'yellow', 'abnormal'],
['Pear', 'green', 'abnormal']
]
app_keys = {}
for sub_list in app_list:
app_keys["%s_n" % sub_list[0]] = sub_list[0]
app_keys["%s_c" % sub_list[0]] = sub_list[1]
app_keys["%s_s" % sub_list[0]] = sub_list[2]
why wouldn't you do a dictionary of lists?
y = {}
for a in range (0,16777216):
y[a] = []
also for brevity: https://stackoverflow.com/a/1747827/884453
y = {a : [] for a in range(0,16777216)}
Not sure if this is quite what you want but couldn't you emulate the same behavior by simply creating a list of lists? So your_list[0] would correspond to y0.
I think dictionaries are more suitable for this purpose:
>>> name = ['mike', 'john', 'steve']
>>> age = [20, 32, 19]
>>> dic=dict(zip(name, age))
>>> dic['mike']
20
>>> dic['john']
32
But if you still want to create variables on the fly you can use globals()[]:
>>> for x,y in zip(name, age):
globals()[x] = y
>>> mike
20
>>> steve
19
>>> john
32
You can use globals():
globals()[e] = age[index]
Generally, though, you don't want to do that; a dictionary is much more convenient.
people = {
'mike': 20,
'john': 32,
'steve': 19
}
Use a list comprehension:
[[] for n in range(N)]
or a simple for loop
empt_lists = []
for n in range(N):
empt_lists.append([])
Note that [[]]*N does NOT work, it will use the same pointer for all the items!!!
Ok...possible solution is to generate class attributes, which you can use after:
class MyClass:
pass
myinstance = MyClass() # if you want instance for example
setattr(myinstance, "randomname", "desiredvalue")
print myinstance.randomname # wonderfull!
put it in the list if possible in your case!
This code can help you:
user_contract = ['ZNZ6','TNZ6','ZBZ6']
data = [[1,2,3],[4,5,6],[7,8,9]]
dictionary = dict(zip(user_contract, data))
print(dictionary)
It creates a dictionary from the two lists and prints it:
python3 pyprog.py
{'ZBZ6': [7, 8, 9], 'ZNZ6': [1, 2, 3], 'TNZ6': [4, 5, 6]}
You can use exec to evaluate expressions and assign to variables dynamically:
>>> names = ','.join(user_contract)
>>> exec('{:s} = {:s}'.format(names, str(data)))
Forget filtering locals()! The dictionary you give to the formatting string is allowed to contain unused keys:
>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> locals()
{'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...}
>>> '%(name)s %(zip)i' % locals()
'foo 123'
With the new f-string feature in Python 3.6, using locals() is no longer necessary:
>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> f'{zip: >5} {name.upper()}'
' 123 FOO'
You can use list or generator comprehensions to build a list of key, value tuples used to directly instantiate a dict. The best way is below:
dict((name, eval(name)) for name in list_of_variable_names)
In addition, if you know, for example, that the variables exist in the local symbol table you can save yourself from the dangerous eval by looking the variable directly from locals:
dict((name, locals()[name]) for name in list_of_variable_names)
After your final update, I think the answer below is really what you want. If you're just using this for string expansion with strings that you control, just pass locals() directly to the string expansion and it will cherry-pick out the desired values
If, however, these strings could ever come from an outside source (e.g. translation files), than it's a good idea to filter locals()
Hello , I'm trying to create several name lists automatically . because I want to to create a data frame with them. For example :
List_1= [1,2,3]
List_2= [10,11,12]
etc....
afterwards I would like to create a unique dictionary for every one of them so that I can convert it into a dataframe with pandas
dic1= {'A': List_1, 'B': List_2. etc...}
but Im having trouble creating the unique list names, I have tried using formatted strings with for loop, but Im just getting the name and not the data points. I would really appreciate your help in this matter. Thank u
You could use a dictionary like this:
character = {'Name': 'Mary', 'xPos': 0, 'yPos': 0}
character['xPos'] = 10
A dict would work, but a class is a better fit IMO.
class Character:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
arthur = Character(9, 9)
arthur.x = 15
Due credit to AChampion for posting the class in a comment
You can do it with a dictionary:
mylist = ["a", "b", "c", "d"]
mydict = {}
for item in mylist:
mydict[item] = input("What do you want " + str(item) + " to be defined as?")
More about dictionaries you can read here: https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries
I suggest to use a dict instead of a list, so that the dict will represent a mapping between variable names and their associated value:
variables = ['a', 'b', 'c']
mapping = {v: None for v in variables}
for variable in variables:
mapping[variable] = input(...)
Anyway, if you really need to dynamically create new variable, you can still rely on exec:
var = 'a'
value = 'apple'
# Similar to a = 'apple'
exec('{} = "{}"'.format(var, value))
After having executed those lines, you can check that a is defined and has the correct value:
assert a == 'apple'
Btw, relying on exec is not a good idea in general (especially if you have no control on what is provided to input!).
Use dict instead of globals
Use of global variables is not recommended practice. Much cleaner and easily maintainable is a dictionary of dictionaries. For example, using a dictionary comprehension:
fruits_lst = ['apples', 'oranges', 'bananas', 'guavas']
d = {fruit: {} for fruit in fruits_lst}
Then access a particular inner dictionary via d['apples'], d['oranges'], etc.
See this answer for an explanation why this is useful, and here for another example.
Everything in Python is a dictionary, even the scope.
You can use globals() for it:
fruits_lst = ['apples','oranges','bananas','guavas']
globals().update({name : dict() for name in fruits_lst})
apples["foo"] = 10
print(apples)
Results are:
{'foo': 10}