Home > front end >  Creating separate dictionaries with a list of values in it
Creating separate dictionaries with a list of values in it

Time:12-20

I have a dictionary like this :

dict = {'hosts': [{'hostname': 'abc', 'ip': '127.0.0.1', 'extra_check_cmd': 'check-me'}, {'hostname': 'def', 'ip': '127.0.0.2', 'extra_check_cmd': 'check-it,check-this'}, {'hostname': 'ijk,uvw,xyz', 'ip': '127.0.0.3,127.0.0.4,127.0.0.5', 'extra': 'check-me'}]}

I want to create the following dictionary out of it

dict = {'hosts': [{'hostname': 'abc', 'ip': '127.0.0.1', 'extra_check_cmd': 'check-me'}, {'hostname': 'def', 'ip': '127.0.0.2', 'extra_check_cmd': 'check-it'},{'hostname': 'def', 'ip': '127.0.0.2', 'extra_check_cmd': 'check-this'},{'hostname': 'ijk', 'ip': '127.0.0.3', 'extra': 'check-me'},{'hostname': 'uvw', 'ip': '127.0.0.4', 'extra': 'check-me'},{'hostname': 'xyz', 'ip': '127.0.0.5', 'extra': 'check-me'}]}

That means each list of values should have a separate sub-dictionaries wherever list of values are given.

CodePudding user response:

Maybe something like this?

def expand_dict(host):
    kv_pairs = [[(k, v) for v in vals.split(",")] for k, vals in host.items()]
    max_len = max(len(p) for p in kv_pairs)
    assert all(len(pairs) in {1, max_len} for pairs in kv_pairs)
    updated_pairs = [p if len(p) == max_len else p * max_len for p in kv_pairs]
    return (dict(pairs) for pairs in zip(*updated_pairs))

input_dict = {'hosts': [{'hostname': 'abc', 'ip': '127.0.0.1', 'extra_check_cmd': 'check-me'}, {'hostname': 'def', 'ip': '127.0.0.2', 'extra_check_cmd': 'check-it,check-this'}, {'hostname': 'ijk,uvw,xyz', 'ip': '127.0.0.3,127.0.0.4,127.0.0.5', 'extra': 'check-me'}]}
output_dict = {'hosts': [d for host in input_dict['hosts'] for d in expand_dict(host)]}

Also, I wouldn't recommend naming a variable dict like you did in your example. dict is also the name of the builtin dict function, which your variable would shadow.

  • Related