Search code examples
python-3.xlist-comprehensiondictionary-comprehension

Comprehension with Lists of Dictionaries


I know this isn't exactly the first question about list comprehensions, but I've been looking around and experimenting for a while and can't figure this one out. I'll apologize in advance, I'm a self-taught novice learning from failures.

This is working code, but it screams list comprehension. I understand list comprehensions and use them, but the combination of stacking for and working with the dictionaries within the lists is breaking my brain. How would you simplify this:

results = []
for system in systems:  # list of dicts
    for result in telnet_results:   # list of dicts
        if system['master_ip'] == result['master_ip']:
            combined = {**system, **result}  # merge dicts, right takes precedence
            results.append(combined)

Thanks in advance for any help on this.


Solution

  • results = [{**system, **result} for system in systems for result in telnet_results if 
               system['master_ip'] == result['master_ip']]
    

    Can be also splitted more logically:

    results = [{**system, **result}
               for system in systems
               for result in telnet_results
               if system['master_ip'] == result['master_ip']]
    

    Is this "simplified"? I'm not sure. List comprehensions are not magic, and they do not always simplify the code or make it more readable.