Compare the keys of two nested dictionaries with level 3 - python

I have two nested dictionary: main and test. I want to compare the keys of the dictionaries and find the difference.
main = {"A":{"AA":{"AAA1": [1, 3], "AAA2": [2,4]}, 'BB': {'BBB1': [2 ,4 ], 'BBB2': [5,7]}}}
test1 = {"A":{"AA":{"AAA1": [3, 3], "AAA2": [4,4]}, 'BB': {'BBB1': [4 ,4 ], 'BBB2': [7,7]}}}
test2 = {"A":{"AA":{"AAA1": [3, 3], "AAA2": [4,4]}, 'BB': {'BBB1': [4 ,4 ]}}}
When comparing main and test1, the expected output is {} as all keys till level 3 are present.
When comparing main and test2, the expected output is {'A': {'BB': ['BBB2']}}.
I have tried the solution for three levels using the How to get the difference between two dictionaries in Python? Is there any other efficient method for nested dictionaries? Thanks in advance.

Related

how to create a dictionary having different number of values at different keys?

Question.1 ) I want to create a dictionary , it consist of 8 keys , some keys has 2 values and some keys have 3 values. how to create this kinda dictionary in python.
i been trying using nested loops , but my logic didn't worked.
Desired output
dict_a = { 1:[0,1], 2:[2,3], 3:[4,5], 4:[6,7], 5:[8,9], 6:[10,11], 7:[12,13,14], 8:[15,16,17] }
Question.2 ) If we successfully create the dict_a then, In the second part, i want to merge the multiple values of dict_a according to the dict_b,shown below.
for example :- In dict_b = { 1:[1,2], 2:[2,3]......} ,Here 1:[1,2] means I want to merge 1st and 2nd 'values' of dict_a dictionary, which will give me [0, 1, 2, 3]. similarly 2:[2,3] will give me [2,3,4,5]
dict_b = { 1:[1,2], 2:[2,3], 3:[3,4], 4:[4,5], 5:[5,6], 6:[6,7], 7:[7,8] }
I actually tried the above method successfully, but for two keys 7thand 8th in dict_a , i want to merge with first two values only, i.e when dict_b goes to it's 7th key 7:[7,8], i want the result to be [12,13,15,16] and not [12,13,14,15,16,17].
but the method i used below will merge all inevitably.
dict_a = { 1:[0,1], 2:[2,3], 3:[4,5], 4:[6,7], 5:[8,9], 6:[10,11], 7:[12,13,14], 8:[15,16,17] }
dict_b = { 1:[1,2], 2:[2,3], 3:[3,4], 4:[4,5], 5:[5,6], 6:[6,7], 7:[7,8] }
a_list = []
for i in dict_b:
tem = []
a_list.append(tem)
for j in dict_b[i]:
tem.extend(dict_a[j])
print(tem)
Desired output-
[0, 1, 2, 3]
[2, 3, 4, 5]
[4, 5, 6, 7]
[6, 7, 8, 9]
[8, 9, 10, 11]
[10, 11, 12, 13]
[12, 13, 15, 16]
If you only want to merge with the first 2 values, use a slice.
Change
tem.extend(dict_a[j])
to
tem.extend(dict_a[j][:2])

Pandas: Looking to avoid a for loop when creating a nested dictionary

Here is my data:
df:
id sub_id
A 1
A 2
B 3
B 4
and I have the following array:
[[1,2],
[2,5],
[1,4],
[7,8]]
Here is my code:
from collections import defaultdict
sub_id_array_dict = defaultdict(dict)
for i, s, a in zip(df['id'].to_list(), df['sub_id'].to_list(), arrays):
sub_id_array_dict[i][s] = a
Now, my actual dataframe includes a total of 100M rows (unique sub_id) with 500K unique ids. Ideally, I'd like to avoid a for loop.
Any help would be much appreciated.
Assuming the arrays variable has same number of rows as in the Dataframe,
df['value'] = arrays
Convert into dictionary by grouping
df.groupby('id').apply(lambda x: dict(zip(x.sub_id, x.value))).to_dict()
Output
{'A': {1: [1, 2], 2: [2, 5]}, 'B': {3: [1, 4], 4: [7, 8]}}

How to write a unique dictionary within dictionary with list as keys to a csv file?

I have a dictionary, in which each key has one unique dictionary as its value. Now the value for each of these keys is a list. For example:
d = {'date1': {'name1': [1, 2], 'name2': [2, 4, 2]}, 'date2': {'name1': [4, 5, 6]}}
My goal is to write this dictionary to csv files. I would like to have the file name be the key values of the outer dictionary (date1.csv, date2.csv), where each of these files have the inner dictionary keys as columns with the values going down the columns. Using our example:
date1.csv
name1 name2
1 2
2 4
2
I have tried to loop through the outer dictionary, open a csv file with the name of this key to write, but I cannot figure out how to manage making the lists as values in the columns.
Thanks in advance.
For simplicity use pandas
import pandas as pd
d = {'date1': {'name1': [1, 2], 'name2': [2, 4, 2]}, 'date2': {'name1': [4, 5, 6]}}
for filename in d:
df = pd.DataFrame({key:pd.Series(value) for key, value in d[filename].items() })
df.to_csv(filename+'.csv')
This was a fun one.
import itertools
d = {'date1': {'name1': [1, 2], 'name2': [2, 4, 2]}, 'date2': {'name1': [4, 5, 6]}}
for k,v in d.items():
with open(k+'.csv','w') as fout:
print( ','.join(v.keys()), file=fout)
for cols in itertools.zip_longest(*v.values()):
cols = ['' if i is None else str(i) for i in cols]
print( ','.join(cols), file=fout )
[timr#Tims-Pro:~/src]$ python x.py
[timr#Tims-Pro:~/src]$ cat date1.csv
name1,name2
1,2
2,4
,2
[timr#Tims-Pro:~/src]$ cat date2.csv
name1
4
5
6
[timr#Tims-Pro:~/src]$

Python 3: How to compare two tuples and find similar values?

I have two dictionaries: (1)Inventory and (2)Items
Under these dictionaries are tuples which are added using user's input.
dict_inventory = {('fruits', ['apple','mango'])
dict_items = {('apple', [3, 5])
('mango', [4, 6])}
How do I compare the two and to match similar values which are apple and mango
My code is not printing anything:
for itemA in dict_inventory.values():
for itemB in dict_items.keys():
if itemA == itemB:
print("Match!")
Your original for-loop was getting the values from the inventory dictionary as a list rather than a string when you iterated through the values. Since it returned a list, you will need to iterate through those values as well. This should get you running:
inventory = {
"fruits": ["apples", "mangos",]
}
items = {
"apples": [3, 5],
"mangos": [4, 6],
}
for value in inventory.values():
for item_a in value:
if item_a in items.keys():
print("Match!")
However, you could just merge the two dictionaries.
inventory = {
"fruits": {
"apples": [3, 5],
"mangos": [4, 6],
}
}

Merging two different lists of datetime intervals

I'm trying to merge two lists. Each list has a start date, end date and a value. Resulting list must have both values. Intervals from list 2 will need to be split when intervals don't match. I'm able to this going day by day and obtaining values from both lists. However, this is extremely inefficient, so it won't work with big lists. I would like to know what is the most efficient way of doing this
Here's an example:
LIST 1
[
['ALL', 'ALL', 2],
['2013-11-24', '2013-11-30', 4],
['2013-12-24', '2014-01-01', 3],
]
LIST 2
[
['2013-07-08', '2013-08-29', '1800.00'],
['2013-08-30', '2013-09-06', '1800.00'],
['2013-10-01', '2013-10-31', '1500.00'],
['2013-11-24', '2013-12-03', '400.00'],
['2013-12-24', '2014-01-03', '500.00'],
]
RESULTING LIST
[
['2013-07-08', '2013-08-29', '1800.00', 2],
['2013-08-30', '2013-09-06', '1800.00', 2],
['2013-10-01', '2013-10-31', '1500.00', 2],
['2013-11-24', '2013-11-30', '400.00', 4],
['2013-12-01', '2013-12-03', '400.00', 2],
['2013-12-24', '2014-01-01', '500.00', 3],
['2014-01-02', '2014-01-03', '500.00', 2]
]
I would appreciate any help. Thank you.

Categories