sam
sam

Reputation: 19

how to print dictionary key with first element of nested list

I have a dictionary which value is nested list. for example:

d = {1: [[2, 5], [3, 4]]}

how can I make link key with first element of nested list and print

[[1, 2], [1, 3]]

Upvotes: 1

Views: 996

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

You can use simple list comprehension, like this

>>> d = {1: [[2, 5], [3, 4]]}
>>> [[key, value[0]] for key in d for value in d[key]]
[[1, 2], [1, 3]]

This can be understood, like this

>>> result = []
>>> for key in d:
...     for value in d[key]:
...         result.append([key, value[0]])
... 
>>> result
[[1, 2], [1, 3]]

Or with dict.items,

>>> result = []
>>> for key, values in d.items():
...     for value in values:
...         result.append([key, value[0]])
...         
>>> result
[[1, 2], [1, 3]]

The main idea is, we iterate over the keys of the dictionary with for key in d and for every key, we get the value corresponding to it with d[key] and iterate the elements of it, to prepare the result in the form [key, value[0]].

Upvotes: 2

Related Questions