anon pineapple
anon pineapple

Reputation: 17

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?

Upvotes: 0

Views: 66

Answers (1)

BrokenBenchmark
BrokenBenchmark

Reputation: 19262

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]}}

Upvotes: 3

Related Questions