python - How to make a list formed by changing some defaults in multiple ways -
i have list of default dictionaries:
default = [{"one": 1, "two": 2, "three": 3}, {"one": 5, "two": 6, "three": 7}, {"one": 9, "two": 10, "three" : 11}]
all same keys. have separate dictionary key list:
varying = {"one": [12,13,14,15], "two": [20,21,23], "three": [12,44]}
what want make list of dictionaries possible made changing 1 of values in 1 of default dictionaries 1 of corresponding values in varying dictionary. here examples of dictionaries in final list:
{"one": 12, "two": 2, "three": 3} {"one": 13, "two": 2, "three": 3} {"one": 14, "two": 6, "three": 7} {"one": 15, "two": 10, "three": 11} {"one": 5, "two": 20, "three": 7} {"one": 9, "two": 23, "three": 11} {"one": 1, "two": 2, "three": 44}
so overall there (4+3+2)*3=27 possibilities. able near working problem got messy. there clean way this?
default = [{"one": 1, "two": 2, "three": 3}, {"one": 5, "two": 6, "three": 7}, {"one": 9, "two": 10, "three" : 11}] varying = {"one": [12,13,14,15], "two": [20,21,23], "three": [12,44]} result = [dict(d.items() + [(k, x)]) d in default k, v in varying.items() x in v] >>> result [{'one': 1, 'three': 12, 'two': 2}, {'one': 1, 'three': 44, 'two': 2}, {'one': 1, 'three': 3, 'two': 20}, {'one': 1, 'three': 3, 'two': 21}, {'one': 1, 'three': 3, 'two': 23}, {'one': 12, 'three': 3, 'two': 2}, {'one': 13, 'three': 3, 'two': 2}, {'one': 14, 'three': 3, 'two': 2}, {'one': 15, 'three': 3, 'two': 2}, {'one': 5, 'three': 12, 'two': 6}, {'one': 5, 'three': 44, 'two': 6}, {'one': 5, 'three': 7, 'two': 20}, {'one': 5, 'three': 7, 'two': 21}, {'one': 5, 'three': 7, 'two': 23}, {'one': 12, 'three': 7, 'two': 6}, {'one': 13, 'three': 7, 'two': 6}, {'one': 14, 'three': 7, 'two': 6}, {'one': 15, 'three': 7, 'two': 6}, {'one': 9, 'three': 12, 'two': 10}, {'one': 9, 'three': 44, 'two': 10}, {'one': 9, 'three': 11, 'two': 20}, {'one': 9, 'three': 11, 'two': 21}, {'one': 9, 'three': 11, 'two': 23}, {'one': 12, 'three': 11, 'two': 10}, {'one': 13, 'three': 11, 'two': 10}, {'one': 14, 'three': 11, 'two': 10}, {'one': 15, 'three': 11, 'two': 10}]
here equivalent using normal loops instead of list comprehension:
result = [] d in default: k, v in varying.items(): x in v: result.append(dict(d.items() + [(k, x)]))
note on python 3.x need use list(d.items())
instead of d.items()
.
Comments
Post a Comment