Skip to content

Instantly share code, notes, and snippets.

@gdementen
Forked from kentquirk/petowner_comprehension1.py
Last active September 16, 2016 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdementen/7d1f2564fdf45d225265660f680468b1 to your computer and use it in GitHub Desktop.
Save gdementen/7d1f2564fdf45d225265660f680468b1 to your computer and use it in GitHub Desktop.
Set up output first
# 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:
output[element["owner"]].append(element["pet"])
# 4) if not available, use dict on a generator of tuples: this is a lot more readable/idiomatic IMO.
output = dict((e["owner"]: []) for e in elements)
for element in elements:
output[element["owner"]].append(element["pet"])
# 5) in last resort, use a dict on list comprenhension. But in that case, please use a list of *tuples*, this is still more readable/idiomatic than a list of lists IMO.
output = dict([(e["owner"]: []) for e in elements])
for element in elements:
output[element["owner"]].append(element["pet"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment