This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 1) like others pointed out, you should use a defaultdict in this case | |
# 2) otherwise use setdefault | |
output = {} | |
for element in elements: | |
output.setdefault(element["owner"], []).append(element["pet"]) | |
# 3) if, for some reason, this does not work in your case, use a dict comprehension (if available for your version of Python, 2.7+ I think) | |
output = {e["owner"]: [] for e in elements} | |
for element in elements: |