1

I have a solution to this question, but I'm curious if there might be a better way. I have a dict like this:

dict1 = {
'key1':[['value1','value2','value3'],['value4','value5','value6']],
'key2':[['value7','value8','value9'],['value10','value11','value12']],
'key3':[['value13','value14','value15'],['value16','value17','value18']]}

I want to convert this into a nested list, and inserting the keys into the new sublist like this:

nestedlist = [
['value1','value2','key1','value3'],['value4','value5','key1','value6'],
['value7','value8','key1','value9'],['value10','value11','key2','value12'],
['value13','value14','key2','value15'],['value16','value17','key2','value18'],
['value10','value11','key3','value12'],['value13','value14','key3','value15'],
['value16','value17','key3','value18']]

I solve this the following way:

keys = [*dict1]
newlist = []
for item in keys:
    for item2 in dict1[item]:
        item2.insert(2,item)
        newlist.append(item2)

so, how can i improve this piece of code?

2 Answers 2

3

Here is one way via a list comprehension:

res = [[w[0], w[1], k, w[2]] for k, v in dict1.items() for w in v]

# [['value1', 'value2', 'key1', 'value3'],
#  ['value4', 'value5', 'key1', 'value6'],
#  ['value7', 'value8', 'key2', 'value9'],
#  ['value10', 'value11', 'key2', 'value12'],
#  ['value13', 'value14', 'key3', 'value15'],
#  ['value16', 'value17', 'key3', 'value18']]
Sign up to request clarification or add additional context in comments.

2 Comments

this method was the fastest, ill give you the correct answer :)
I was trying list comprehension at first but for some reason couldn't get it even though I've done multi nested list comp before. Thanks for posting this
1

I would've done it pretty similarly. The only differences shown here:

result = []
for k, l in dict1.items():
   for ll in l:
      ll.insert(2, k)
      result.append(ll)

No need to do list unpacking or doing [] accessing on dict1. items() returns a list of tuples containing each key and value of the dict.

1 Comment

Maybe there's something you can do with list(), map(), and lambdas but I'm not near a machine with python on it to test it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.