'Building a dictionary from a 2D list

def somedict(dataList):
print(somedict([["monkeys", 5, 8, 3, 5], ["bananas", 2, 2, 3]]))

lets say I have something like above, where I want to take a 2D list and convert it into a dictionary without slicing.

So that the output would be:

{'monkeys': {'count': [5, 8, 3, 5]}, 'bananas': {'count': [2, 2, 3]}}

What are some methods for this?



Solution 1:[1]

You can use list unpacking with a dictionary comprehension to avoid explicit slicing or indexing:

result = {fst: {'count': rest} for fst, *rest in data}
print(result)

This outputs:

{'monkeys': {'count': [5, 8, 3, 5]}, 'bananas': {'count': [2, 2, 3]}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1