Python loop dict in assigned order [duplicate] - python

This question already has answers here:
Order of keys in dictionaries in old versions of Python
(6 answers)
Closed 8 years ago.
I've run into a problem with looping through a dictionary. The following code:
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
for k,v in d.iteritems():
print k,v
Results in:
a 1
c 3
b 2
But the desired result is:
a 1
b 2
c 3
Does anyone know how to fix the loop somehow to preserve the order that the elements were assigned in? Thank you!

In Python, normal dictionaries were designed to be unordered. Meaning, they should not be used here.
Instead, you should use a collections.OrderedDict:
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d['a'] = 1
>>> d['b'] = 2
>>> d['c'] = 3
>>> for k,v in d.iteritems():
... print k,v
...
a 1
b 2
c 3
>>>
Unlike a normal dictionary, an OrderedDict is guaranteed to preserve the order in which the elements were assigned.

A dictionary does not preserve order, so you need to sort the keys:
for k,v in sorted(d.iteritems,key=lambda x: x[0]):
print k,v
Alternatively, use a collections.OrderedDict object which internally maintains a list of keys in insertion order:
import collections
d = collections.OrderedDict()
...
for k,v in d.iteritems():
print k,v

Related

Is there a more efficient way to delete elements from a dictionary? [duplicate]

This question already has answers here:
filter items in a python dictionary where keys contain a specific string
(6 answers)
Closed 8 months ago.
d = {'a1':1, 'a2':2,'a3':3,'a4':1,'a5':1,'b':2, 'c':3}
for k, v in d.copy().items():
if 'a' in k:
del d[k]
print(d)
I want to delete elements if the key or value meets a certain requirement, as above, in which the keys containing 'a' will be deleted.
In particular, can I somehow not use the copy() function to do the same thing?
EDIT: Based on suggestion, I adopted this way:
for k in list(d):
if 'a' in k:
del d[k]
Create a new dictionary without the key you want to filter
d = {'a1':1, 'a2':2,'a3':3,'a4':1,'a5':1,'b':2, 'c':3}
filtered_d = {k: v for k,v in d.items() if 'a' not in k}

Creating and Sorting a nested dictionary

I have two arrays:-
A=[a,d,b,c]
B=[e,g,f,h,k,l,m]
I want to create a nested dictionary by combing two arrays. I want to insert hello in a nested dictionary for each key pair. Expected result :
d=dict()
d={'a':{'e':'Hello','g':'Hello','f':'Hello','f':'Hello','h':'Hello','k':'Hello','l':'Hello','m':'Hello'},
'b':{'e':'Hello','g':'Hello','f':'Hello','f':'Hello','h':'Hello','k':'Hello','l':'Hello','m':'Hello'},
c:{'e':'Hello','g':'Hello','f':'Hello','f':'Hello','h':'Hello','k':'Hello','l':'Hello','m':'Hello'} --------- }
My code :
for f in range(0,len(A)):
d[f] = {}
for i in range (0,len(B):
if A[f] not in d:
d[f]={}
d[A[f]].update([B[i]]:'Hello')
print d
But what I am getting is the distorted dictionary. I was expecting results as I explained above but I am getting result a dictionary, not in proper order and sorting is messed up.
Please Help.
OrderDict exists in python, but it does remember the order of keys insertion :
from collections import OrderedDict
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
for k,v in d.items():
print(k,v)
#('a',1)
#('c',3)
#('b',2)
ord = {}
ord = {}
ord['a'] = 1
ord['b'] = 2
ord['c'] = 3
for k,v in ord.items():
print(k,v)
#('a',1)
#('b',2)
#('c',3)
Official doc here

How to convert dictionary keys string to variables(parameters) in python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
my problem is that I need a some variables and parameters which are in string form in dictionary and the values are in both shape (string and integer)
For example :
d={'a6':'36','a21':52}
Now I want these to use them in next steps in some math formulas:
a6=36.0
a21=52.0
Is there anyway to change those keys which are in string forms to these variables?
You could just do:
for key,val in d.items():
vars()[key] = int(val)
>> a6
36
You can do it in a single line with:
>>> d = {'a': 1, 'b': 2}
>>> locals().update(d)
>>> a
1
or:
>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
exec(key + '=val')
#list(map(exec, ("{0}={1}".format(x[0],x[1]) for x in d.items())))
Try:
for k, v in d.items():
exec("%s = %s" % (k, v))
Please note that using exec (or eval) can create a substantial security risk if you don't have complete control over the inputs.

iterating dictionaries in Python 3.x [duplicate]

This question already has answers here:
Intersection and Difference of two dictionaries
(2 answers)
Closed 6 years ago.
I am trying to handle values from two different dictionaries in Python.
What I need to do is operate with values which have the same key in both dictionaries.
For instance, if dictionaries are:
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
I need to add values from keys 1, 2 and 3 from each dictionary.
I am trying to make an iterable of values, but, when I try to extend an empty iterable with values with a line such as:
sameKeys.extend(d1[i]))
I get an Error Key. I have tried many differents syntax but none has worked.
You can try like this,
for i,j in zip(d1.items(),d2.items()):
if i[0] == j[0]:
print i[1]+j[1]
Result
70
70
90
Iterate over any of the dict. Check whether key exists in second list. If it exists, make an entry into new dict. Below is the sample example:
>>> d1 = {1:30, 2:20, 3:30, 5:80}
>>> d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
>>> d3 = {}
>>> for key, value in d1.items():
... if key in d2:
... d3[key] = value + d2[key]
...
>>> d3
{1: 70, 2: 70, 3: 90}
>>>
Here is one option:
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
dlist = [d1, d2]
# As a dict comprehension
result = {k: sum(d[k] for d in dlist)
for k in set.intersection(*[set(d) for d in dlist])}
print result
# Same as above, but as for loops
result = {}
repeated_keys = set(d1)
for d in dlist:
repeated_keys &= set(d)
for k in repeated_keys:
result[k] = 0
for d in dlist:
result[k] += d[k]
print result

If in python dictionary, multiple keys are assign to a value then how to get value by using one of the key? [duplicate]

This question already has answers here:
partial match dictionary key(of tuples) in python
(4 answers)
Closed 8 years ago.
d = dict({('a','b'):1})
then how to get value by using either d.get('a') or d.get('b') instead of d.get(('a','b'))
>>> d=dict({('a','b'):1})
>>> d.get('a') // should return value as 1
>>> d.get('b') // should return value as 1
>>> d.get(('a','b'))
1
>>>
You could make a partial match function similar to, but simpler than, the one in this question.
def partial_match(d, part_key):
for key, value in d.items():
if part_key in key:
return value
>>> partial_match(d, 'a')
1
You could create a dedicated data structure derived from dict:
>>> class MyDict(dict):
... def __init__(self, *args):
... if args and type(args[0]) is dict:
... for k, v in args[0].iteritems():
... self.__setitem__(k, v)
... dict.__init__(self, *args)
... def __setitem__(self, keys, val):
... dict.__setitem__(self, keys, val)
... if type(keys) is tuple:
... for k in keys:
... self.__setitem__(k, val)
...
>>> d=MyDict({('a','b'):1})
>>> print d.get('a')
1
>>> print d.get('b')
1
>>> print d.get(('a','b'))
1
>>>
This creates new entries in the dictionary as suggested by #Thrustmaster.
The alternative is to create a 'partial match' function as #Stuart has proposed, that uses less memory as entries are not duplicated, but using more computations as it requires looping through all keys, effectively making the key hashes useless.
As pointed out in the comments, dictionary is simply a key-value mapping. You give it a single key, it will return a uniquely identifiable value against it.
To be able to get the value from the dict using any of the elements in the tuple, then you'd need to use something like the below:
>>> def updateDict(d, obj):
... for key, value in obj.items():
... for k in key:
... d[k] = value
...
>>> res = {}
>>> updateDict(res, {('a','b'):1})
>>> res
{'a': 1, 'b': 1}
>>> res['a']
1
>>> res['b']
1
Note that the code above merely inserts the values multiple time one for each element in the tuple.
You can create the dictionary you want using the original dict:
d1 = dict({('a','b'):1})
# creates {'a':1, 'b':1 }
d2 = {x:v for k, v in d1.items() for x in k}
print d2.get('a') # prints 1
print d2.get('b') # prints 1

Categories