How to split a python dictionary for its values on matching a key

2024/11/24 5:30:22
my_dict1 = {'a':1, 'chk':{'b':2, 'c':3}, 'e':{'chk':{'f':5, 'g':6}} }

I would like to loop through the dict recursively and if the key is 'chk', split it.
Expected output:

{'a':1, 'b':2, 'e':{'f':5}}
{'a':1, 'c':3, 'e':{'f':5}}
{'a':1, 'b':2, 'e':{'g':6}}
{'a':1, 'c':3, 'e':{'g':6}}

Not sure of how to achieve this. Please help.
What I have tried is below.

temp_list =[]
for k,v in my_dict1.iteritems():temp ={}if k is "chk":for key,val in v.iteritems():temp[key] = valmy_dict1[k]={}for ky,vl in temp.iteritems():my_new_dict = copy.deepcopy(my_dict1)for k,v in my_new_dict.iteritems():if k is "chk":my_new_dict[k] = {ky:vl}temp_list.append(my_new_dict)
print temp_list

output:

[{'a': 1, 'chk': ('c', 3), 'e': {'chk': {'f': 5, 'g': 6}}},{'a': 1, 'chk': ('b', 2), 'e': {'chk': {'f': 5, 'g': 6}}}]

How to make it recursive?

Answer
from itertools import productmy_dict = {'a':1, 'chk':{'b':2, 'c':3}, 'e':{'chk':{'f':5, 'g':6}} }def process(d):to_product = []  # [[('a', 1)], [('b', 2), ('c', 3)], ...]for k, v in d.items():if k == 'chk':to_product.append([(k2, v2) for d2 in process(v) for k2, v2 in d2.items()])elif isinstance(v, dict):to_product.append([(k, d2) for d2 in process(v)])else:to_product.append([(k, v)])lst = [dict(l) for l in product(*to_product)]unique = [][unique.append(item) for item in lst if item not in unique]return uniquefor i in process(my_dict):print(i)# {'e': {'f': 5}, 'b': 2, 'a': 1}
# {'e': {'g': 6}, 'b': 2, 'a': 1}
# {'e': {'f': 5}, 'a': 1, 'c': 3}
# {'e': {'g': 6}, 'a': 1, 'c': 3}
https://en.xdnf.cn/q/120571.html

Related Q&A

PyException: ImportError: No module named domreg

I am getting the below error while running this script ("from xml.dom import minidom") from chaquopy androi application python console. PyException: ImportError: No module named domreg

Plotting polynomial with given coefficients

Im trying to plot a polynomial with coefficients given in array:input: [an,a(n-1),...,a0] output: plot of polynomial anx^n + a(n-1)x^(n-1) + ... + a0I would like to use matplotlib polt() function so I…

grouping data using unique combinations

n my below data set, I need to find unique sequences and assign them a serial no ..DataSet :user age maritalstatus product A Young married 111 B young married 222 C young Single 111 D…

Python - Sorting in ascending order in a txt file

I had a huge document that I parsed using regex to give a txt file (json.dump) similar to the following:{"stuff": [{"name": ["frfer", "niddsi", ], "number&q…

How to make setuptools install a wheel containing multiple packages?

Suppose this wheel:M Filemode Length Date Time File - ---------- -------- ----------- -------- --------------------------------------------rw-rw-r-- 1358 26-Sep-2018 21:08…

Python - Randomly select words to display in a quiz [duplicate]

This question already has answers here:How can I randomly select (choose) an item from a list (get a random element)?(18 answers)Closed 9 years ago.Im in need of some help. Here we have my two lists:w…

How to extract only the english words from the list?

I tried to extract only the English words from the following list: l = [0, b, x14, x00, x1fP, xe0O, xd0, xea, i, x10, xa2, xd8, x08, x00, 00, x9d, x14, x00, x80, xcc, xbf, xb4, xdbLB, xb0, x7f, xe9, x9…

Javascript variable with html code regex email matching

This python script is not working to output the email address [email protected] for this case.This was my previous post.How can I use BeautifulSoup or Slimit on a site to output the email address from …

how to send a large array over tcp socket in python? is it possible to send? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…