Making (theoreticly) infinite dictionaries in python? [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 8 years ago.
I recently looked up this topic but dint find a satisfying answer. Everybody said using dictionaries is the best way , but I don’t know how to apply that in this case:
I want a function that generates me a list of objects generated by a class.
So in pseudo-code something like :
for a in range(100):
tmp = "object" + str(a)
var(tmp) = someclass()
list add tmp
Edit , because of being marked as an duplicate.
I don’t want an answer how dictionary work , I know that. I want to know , how I can make entries which consists of an entry-name and the generated objects for that name.
I need a dictionary which looks something like:
{"1" : obj1 , "2" : obj2, "3" : obj3 ... }
Edit two:
I ended up using a list instead of a dictionary which is massively easier:
for tmp in range(100):
tmpobj = objclass()
list.append(tmpobj)
thanks for help ;)

You can use a dictionary comprehension :
{ var("object" + str(a)) : someclass() for a in range(100) }

Related

How to add int numbers to json data? [duplicate]

This question already has answers here:
What does enumerate() mean?
(7 answers)
Closed 2 years ago.
I have a small script that create JSON. I want to add field track_ID and this field wll be int. Idea is to add some loop in which it starts from 1 and finish when objects gone.
Any ideas?
for list in obj['frames']['objects']:
data = {
'track_ID':
'object_id': obj['info']['doc']
}
Just add an i in it, something like this
i = 0
for list in obj['frames']['objects']:
data = {
'track_ID': i
'object_id': obj['info']['doc']
}
i = i + 1
enumerate() will do that beautifully
You can use enumerate.
Note that your loop overrides the value of data in every iteration, list is a saved word in python and you don't actually use the value of list in your code example.
for idx, list in enumerate(obj['frames']['objects']):
data = {
'track_ID': idx+1
'object_id': obj['info']['doc']
}

creating a variable with name as same as the name of items in list [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
just a stupid question out of curiosity.
Lets say there's a list with elements as
fruits_lst = ['apples','oranges','bananas','guavas']
Now is it possible to create separate separate dictionaries but with the names as the names of elements in the list?
desired result:
apples=dict()
oranges=dict()
bananas=dict()
guavas=dict()
I know one could easily do it by looking at the names of the elements, but what i want to achieve is somehow the program picks up the element names while iterating through it and then creates empty dictionaries with the same names. Is it possible? Kindly guide me through..
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}
Here's a short way, but let me warn you this isn't a good way to defining variables.
fruits_lst = ['apples','oranges','bananas','guavas']
for fruit in fruits_lst:
globals()[fruit] = dict()
Now you can access them directly,
>>> apples
{}
>>> oranges
{}
and so on...

Using a string as variable [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I have a string, which is a variable name. I have to pass that variable to another function to get proper output. I tried using backtick and other techniques. What are the other ways to do that? I am a beginner and don't have much expertise in python.
for i in range(1,65):
period_writer.writerow([i, max('test' + `i`)])
I want to pass the variable as test1, test2, ..... test64 to max() function and get the maximum value of those variables.
Thanks in advance
You are trying to do this:
test1 = something
test2 = something else
for i in range(1,2):
print('test' + str(i))
however, that won't work because strings cannot be used as variable names. You can cheat somewhat by using locals(), which creates a dictionary of local variables:
test1 = something
test2 = something else
for i in range(1,2):
print(locals()['test' + str(i)])
but what you really should be doing is putting your variables into a dictionary (or list!) in the first place.
d = {'test1': something,
'test2': something else}
for i in range(1,2):
print(d['test' + str(i)])
# or even better
tests = [something, something else]
for test in tests:
print(test)
# even better, what you're trying to do is this:
for i, test in enumerate(tests):
period_writer.writerow([i+1, max(test)])
This makes it much clearer that the variables belong together and will run faster to boot.

Randomly shuffling a list of dictionaries [duplicate]

This question already has answers here:
Shuffling a list of objects
(25 answers)
Closed 6 years ago.
A similar question I saw on Stack Overflow dealt with a dict of lists (was a bad title), and when I tried using random.shuffle on my list of dicts per that answer, it made the whole object a None-type object.
I have a list of dictionaries kind of like this:
[
{'a':'1211', 'b':'1111121','c':'23423'},
{'a':'101', 'b':'2319','c':'03431'},
{'a':'3472', 'b':'38297','c':'13048132'}
]
I want to randomly shuffle like this.
[
{'a':'3472', 'b':'38297','c':'13048132'},
{'a':'1211', 'b':'1111121','c':'23423'},
{'a':'101', 'b':'2319','c':'03431'}
]
How can I do this?
random.shuffle should work. The reason I think you thought it was giving you a None-type object is because you were doing something like
x = random.shuffle(...)
but random.shuffle doesn't return anything, it modifies the list in place:
x = [{'a':'3472', 'b':'38297','c':'13048132'},
{'a':'1211', 'b':'1111121','c':'23423'},
{'a':'101', 'b':'2319','c':'03431'}]
random.shuffle(x) # No assignment
print(x)

How can I generate variables with 100 indices? [duplicate]

This question already has answers here:
How to programmatically set a global (module) variable?
(3 answers)
Closed 8 years ago.
I'm very beginner at python and gurobipy library,
and I want to generate bunch of individual variables with indices, like x1, x2, ... ,x100...
Is there any faster and easier way to generate them?
I tried "for" structure in various form but shell keeps returning syntax error message... :(
HELP PLEASE!
If you just want a group of values that can be indexed, use a list (indexes are 0 start):
mylist = ["some item", 23, "other item", 99]
twentythree = mylist[1]
You can add items to the list with .append(<item>):
mylist.append("new item")
You can make a list of 100 items with range(100), but the resulting list will contain values 0 to 99.
Can't say that I like doing it this way - but whenever you have to do such tedious work manually...
for i in range(1,101):
globals()["x{}".format(i)] = "test"
print x53 # prints test

Categories