Using locals() to create a list of dictionaries - python

This might be simple, but I'm stuck. I have globals() that creates dictionaries based on zipping lists (that will differ in sizes, thus differ in the number of the dictionaries that get created). The new dictionaries that get created look like the below:
dict0 = {foo:bar}
dict1 = {more_foo:more_bar}
How do I call these new dictionaries in a for loop?
I want my script to do the below:
for i in (dict0, dict1):
The only issue is that the number of dictx (dictionaries) will differ based on the inputs from the script.

As nicely put in comments, in your case, you should append the dictionaries to a list:
list_iterator = list()
# create dict 1.
list_iterator.append(dict1)
# create dict 2.
list_iterator.append(dict2)
# and so on. If your dict create algorithm is repetetive, you can add the append command to the end.

I figured it out...
for i in range(len(someList)):
dicts = locals()['dict' + str(i)]

Related

Python: using a loop to do the same with several variables

I have 30 variables with the pattern aod7039, aod7040, ...., aod7068.
I want to do the same operation (i.e. calculate the mean over an axis) for all these variables and overwrite the original variables.
Up to now I wrote 30 times the same line, and wondered if there isn't maybe an shorter and easier way to do this?
I am gradeful for every idea!
Firstly, don't use 30 variables, use a list aod[]
Secondly, use
for i in range(7039, 7069):
aod[i] = yourFunction(aod[i])
to override existing list
This will get you all values of variables that start with 'aod'
values = [v for k,v in globals() if k.startswith('aod')]
But having 30 variables smells bad.
If I understand your question right, you just want to iterate over those variables?
If so you could keep references on some list/dictionary and then iterate/update this way.
List = []
List.append(aod7039)
for item in List:
#do something
I have 30 variables with the pattern aod7039, aod7040, ...., aod7068
Then you have a design problem - you should have a list or dict instead. Replace all those variables with either a list or dict (or collections.OrderedDict if you need key access while preserving insertion order) and then it's only a matter of iterating over your container, ie
# with a list:
for index, item in enumerate(yourlist):
yourlist[index] = do_something_with(item)
# with a dict or OrderedDict:
for key, item in enumerate(yourdict):
yourdic[key] = do_something_with(item)
store your 30 variables in a list and use map to tackle it without any loop:
varlist=[aod7039, aod7040, ...., aod7068]
result=list(map(yourfunction, varlist))

Best method to store in python [duplicate]

I'm trying to add items to an array in python.
I run
array = {}
Then, I try to add something to this array by doing:
array.append(valueToBeInserted)
There doesn't seem to be a .append method for this. How do I add items to an array?
{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].
To initialize an empty list do this:
my_list = []
or
my_list = list()
To add elements to the list, use append
my_list.append(12)
To extend the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
To remove an element from a list use remove
my_list.remove(2)
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
To initialize an empty dictionary use {} or dict()
Dictionaries have keys and values
my_dict = {'key':'value', 'another_key' : 0}
To extend a dictionary with the contents of another dictionary you may use the update method
my_dict.update({'third_key' : 1})
To remove a value from a dictionary
del my_dict['key']
If you do it this way:
array = {}
you are making a dictionary, not an array.
If you need an array (which is called a list in python ) you declare it like this:
array = []
Then you can add items like this:
array.append('a')
Arrays (called list in python) use the [] notation. {} is for dict (also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
Just for sake of completion, you can also do this:
array = []
array += [valueToBeInserted]
If it's a list of strings, this will also work:
array += 'string'
In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:
Java:
int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};
However, in Python, curly braces are used to define dictionaries, which needs a key:value assignment as {'a':1, 'b':2}
To actually define an array (which is actually called list in python) you can do:
Python:
mylist = [1,2,3]
or other examples like:
mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]
You can also do:
array = numpy.append(array, value)
Note that the numpy.append() method returns a new object, so if you want to modify your initial array, you have to write: array = ...
Isn't it a good idea to learn how to create an array in the most performant way?
It's really simple to create and insert an values into an array:
my_array = ["B","C","D","E","F"]
But, now we have two ways to insert one more value into this array:
Slow mode:
my_array.insert(0,"A") - moves all values ​​to the right when entering an "A" in the zero position:
"A" --> "B","C","D","E","F"
Fast mode:
my_array.append("A")
Adds the value "A" to the last position of the array, without touching the other positions:
"B","C","D","E","F", "A"
If you need to display the sorted data, do so later when necessary. Use the way that is most useful to you, but it is interesting to understand the performance of each method.
I believe you are all wrong. you need to do:
array = array[] in order to define it, and then:
array.append ["hello"] to add to it.

can I compare the keys of two dictionaries that are not in the same order?

I apologize this must be a basic question for using dictionaries. I'm learning python, and the objective I have is to compare two dictionaries and recover the Key and Value entries from both entries that are identical. I understand that the order in dictionaries is not relevant like if one is working with a list. But I adopted a code to compare my dictionaries and i just wanted to make sure that the order of the dictionaries does not matter.
The code I have written so far is:
def compare_dict(first,second):
with open('Common_hits_python.txt', 'w') as file:
for keyone in first:
for keytwo in second:
if keytwo == keyone:
if first[keyone] == second[keytwo]:
file.write(keyone + "\t" + first[keyone] + "\n")
Any recommendations would be appreciated. I apologize for the redundany in the code above. But if someone could confirm that comparing two dictionaries this way does not require the key to be in the same order would great. Other ways of writing the function would be really appreciated as well.
Since you loop over both dictionaries and compare all the combinations, no, order doesn't matter. Every key in one dictionary is compared with every key in the other dictionary, eventually.
It is not a very efficient way to test for matching keys, however. Testing if a key is present is as simple as keyone in second, no need to loop over all the keys in second here.
Better still, you can use set intersections instead:
for key, value in first.viewitems() & second.viewitems():
# loops over all key - value pairs that match in both.
file.write('{}\t{}\n'.format(key, value))
This uses dictionary view objects; if you are using Python 3, then you can use first.items() & second.items() as dictionaries there return dictionary views by default.
Using dict.viewitems() as a set only works if the values are hashable too, but since you are treating your values as strings when writing to the file I assumed they were.
If your values are not hashable, you'll need to validate that the values match, but you can still use views and intersect just the keys:
for key in first.viewkeys() & second.viewkeys():
# loops over all keys that match in both.
if first[key] == second[key]:
file.write('{}\t{}\n'.format(key, first[key]))
Again, in Python 3, use first.keys() & second.keys() for the intersection of the two dictionaries by keys.
Your way of doing it is valid. As you look through both lists, the order of the dictionaries does not matter.
You could do this instead, to optimize your code.
for keyone in first:
if keyone in second: # returns true if keyone is present in second.
if first[keyone] == second[keyone]:
file.write(keyone + "\t" + first[keyone] + "\n")
The keys of a dictionary are effectively a set, and Python already has a built-in set type with an efficient intersection method. This will produce a set of keys that are common to both dictionaries:
dict0 = {...}
dict1 = {...}
set0 = set(dict0)
set1 = set(dict1)
keys = set0.intersection(set1)
Your goal is to build a dictionary out of these keys, which can be done with a dictionary comprehension. It will require a condition to keep out the keys that have unequal values in the two original dictionaries:
new_dict = {k: dict0[k] for k in keys if dict0[k] == dict1[k]}
Depending on your intended use for the new dictionary, you might want to copy or deepcopy the old dictionary's values into the new one.

Python - Collections

Am new to Python, and would like to know, how to store list of different DataTypes inside a dictionary with a Key
for Example -
{[Key1,int1,int1,String1] , [Key2,int2,int2,String2], [Key3,int3,int3,String3] }
how to create Dictionary and add these elements?
Assuming you meant that your data is:
lst = [[Key1,int1,int1,String1] , [Key2,int2,int2,String2], [Key3,int3,int3,String3]]
Then you could do something like:
{x[0]:x[1:] for x in lst}
What you actually have up there is an attempt to create a set out of a bunch of lists -- and that won't work because list objects aren't hashable.

Creating a dictionary composed of distinct copies of another dictionary

In Python, with two dictionaries, simply doing
dict2 = dict1
Will not cause dict2 to be a distinct copy of dict1. They will point to the same thing, so modifying dict2 will perform the same effect on dict1.
One workaround is
dict2 = dict(dict1)
So if I were to modify dict2, it would not affect dict1's values.
In my program, I'm currently making a dictionary that's composed of multiple copies of a previous dictionary. Let's call the previous dictionary temp2, and the current one temp3. I don't know how many copies I'll need in advance, so I thought of doing this:
temp3 = {}
for i in xrange(some_number):
temp3[i] = dict(temp2)
But my debug tests show that if I modify temp3[0]'s dictionary (which, again, is a copy of temp2), then this will also modify temp3[1]'s copy, and temp3[2], etc., so the result is a dictionary that consists of n identical copies of a dictionary, where n = some_number. Does anyone know of a workaround? Thanks.
EDIT: In response to a comment, temp2 is a dictionary composed of values that are lists, so {a: [list1], b: [list2], etc.}.
Try the copy.deepcopy method: http://docs.python.org/2/library/copy.html

Categories

Resources