Creating and Sorting a nested dictionary - python

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

Related

A python program to filter dictionary

Write a python program to filter a dictionary based on values that are the multiples of 6
NOTE:
Take keys as strings and values as integers.
Constraints:
1<=number of key value pairs<=10
Sample test case: keys : a,b,c,d,e,f values:1,2,3,4,5,6 {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} {'f':6}
You can use a dict comprehension.
d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
res = {k:v for k,v in d.items() if v % 6 == 0}
print(res)
old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
#or this it will work totally perfect
#old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13}
print (f"Original dictionary is : {old_dict}")
print()
new_dict = {key:value for (key, value) in old_dict.items() if value % 6 == 0}
print(f"New dictionary with multiple of 6 is : {new_dict}")

Dictionary get value without knowing the key

In python if I have a dictionary which has a single key value pair and if I don't know what the key might be, how can I get the value?
(and if I have a dict with more than 1 key, value pair, how can I return any one of the values without knowing any of the keys?)
You just have to use dict.values().
This will return a list containing all the values of your dictionary, without having to specify any key.
You may also be interested in:
.keys(): return a list containing the keys
.items(): return a list of tuples (key, value)
Note that in Python 3, returned value is not actually proper list but view object.
Other solution, using popitem and unpacking:
d = {"unknow_key": "value"}
_, v = d.popitem()
assert v == "value"
Further to Delgan's excellent answer, here is an example for Python 3 that demonstrates how to use the view object:
In Python 3 you can print the values, without knowing/using the keys, thus:
for item in my_dict:
print( list( item.values() )[0] )
Example:
cars = {'Toyota':['Camry','Turcel','Tundra','Tacoma'],'Ford':['Mustang','Capri','OrRepairDaily'],'Chev':['Malibu','Corvette']}
vals = list( cars.values() )
keyz = list( cars.keys() )
cnt = 0
for val in vals:
print('[_' + keyz[cnt] + '_]')
if len(val)>1:
for part in val:
print(part)
else:
print( val[0] )
cnt += 1
OUTPUT:
[_Toyota_]
Camry
Turcel
Tundra
Tacoma
[_Ford_]
Mustang
Capri
OrRepairDaily
[_Chev_]
Malibu
Corvette
That Py3 docs reference again:
https://docs.python.org/3.5/library/stdtypes.html#dict-views
Two more ways:
>>> d = {'k': 'v'}
>>> next(iter(d.values()))
'v'
>>> v, = d.values()
>>> v
'v'
One more way: looping with for/in through a dictionary we get the key(s) of the key-value pair(s), and with that, we get the value of the value.
>>>my_dict = {'a' : 25}
>>>for key in my_dict:
print(my_dict[key])
25
>>> my_other_dict = {'b': 33, 'c': 44}
>>> for key in my_other_dict:
print(my_other_dict[key])
33
44

Python loop dict in assigned order [duplicate]

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

Python: While Statement = Statement Print associated Values

In Python I currently have a Dictionary with a composite Key. In this dictionary there are multiple occurences of these keys. (The keys are comma-separated):
(A,B), (A,C), (A,B), (A,D), (C,A), (A,B), (C,A), (C,B), (C,B)
I already have something that totals the unique occurrences and counts the duplicates which gives me a print-out similar to this:
(A,B) with a count of 4, (A,C) with a count of 2, (B,C) with a count of 6, etc.
I would like to know how to code a loop that would give me the following:
Print out the first occurance of the first part of the key and its associtated values and counts.
Name: A:
Type Count
B 4
C 2
Total 6
Name: B:
Type Count
A 3
B 2
C 3
Total 8
I know I need to create a loop where the first statement = the first statement and do the following, but have no real idea how to approach/code this.
Here's a slightly slow algorithm that'll get it done:
def convert(myDict):
keys = myDict.keys()
answer = collections.defaultdict(dict)
for key in keys:
for k in [k for k in keys if k.startswith(key[0])]:
answer[key[0]][k[1]] = myDict[k]
return answer
Ultimately, I think what you're after is a trie
Its a little misleading to say that your dictionary has multiple values for a given key. Python doesn't allow that. Instead, what you have are keys that are tuples. You want to unpack those tuples and rebuild a nested dictionary.
Here's how I'd do it:
import collections
# rebuild data structure
nested = collections.defaultdict(dict)
for k, v in myDict.items():
k1, k2 = k # unpack key tuple
nested[k1][k2] = v
# print out data in the desired format (with totals)
for k1, inner in nested.items():
print("%s\tType\tCount" % k1)
total = 0
for k2, v in innner.items():
print("\t%s\t%d" % (k2, v))
total += v
print("\tTotal\t%d" % total)

Summing List of values with similar keys to dictionary

How can I take a list of values (percentages):
example = [(1,100), (1,50), (2,50), (1,100), (3,100), (2,50), (3,50)]
and return a dictionary:
example_dict = {1:250, 2:100, 3:150}
and recalculate by dividing by sum(example_dict.values())/100:
final_dict = {1:50, 2:20, 3:30}
The methods I have tried for mapping the list of values to a dictionary results in values being iterated over rather than summed.
Edit:
Since it was asked here are some attempts (after just writing over old values) that went no where and demonstrate my 'noviceness' with python:
{k: +=v if k==w[x][0] for x in range(0,len(w),1)}
invalid
for i in w[x][0] in range(0,len(w),1):
for item in r:
+=v (don't where I was going on that one)
invalid again.
another similar one that was invalid, nothing on google, then to SO.
You could try something like this:
total = float(sum(v for k,v in example))
example_dict = {}
for k,v in example:
example_dict[k] = example_dict.get(k, 0) + v * 100 / total
See it working online: ideone
Use the Counter class:
from collections import Counter
totals = Counter()
for k, v in example: totals.update({k:v})
total = sum(totals.values())
final_dict = {k: 100 * v // total for k, v in totals.items()}

Categories