KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have a Python list which holds pairs of key/value: l = [[1, 'A'], [1, 'B'], [2, 'C']] I want to convert the list into a dictionary, where multiple values per key would be aggregated into a tuple: {1: ('A', 'B'), 2: ('C',)} The iterative solution is trivial: l = [[1, 'A'], [1, 'B'], [2, 'C']] d = {} for pair in l: if pair[0] in d: d[pair[0]] = d[pair[0]] + tuple(pair[1]) else: d[pair[0]] = tuple(pair[1]) print(d) {1: ('A', 'B'), 2: ('C',)} Is there a more elegant, Pythonic solution for this task?
Tags (comma-separated)
Save Edits
Cancel