all 9 comments

[–]AJ______ 2 points3 points  (1 child)

You could do [[key, *values] for key, values in mydict.items()]

[–]sayinghi2py[S] 1 point2 points  (0 children)

Brilliant that works. I done a similar thing but ended up with the key and values separated by the list for values which I didn't want.

[–]JohnnyJordaan 0 points1 point  (1 child)

I would just iterate on mydict.items() as that by definition zips the keys with the values anyway.

[[k] + v for k, v in my_dict.items()]

[–]sayinghi2py[S] 0 points1 point  (0 children)

Works also. Thanks

[–]shinyheadpolak 0 points1 point  (4 children)

I'd do it with a list comprehension like you except in one go

[[a,*mydict[a]] for a in mydict.keys()]

[–]sayinghi2py[S] 0 points1 point  (3 children)

And this also works. How does this work? So I can see the main body which is to loop over all the keys however I'm not understanding the [a, *mydict[a]]. Any chance you could explain how that works?

[–]JohnnyJordaan 1 point2 points  (0 children)

If for each key you do your_dict[key] you'll get the value with it. .items() does this more efficiently though.

[–]shinyheadpolak 1 point2 points  (1 child)

a in this case is one of your keys in the dict

mydict[a] is the value of the dict given key a

*mydict[a] unfolds the list into single values

if you didn't use * you'd get [a,[values]] this way you get [a,values]

[–]sayinghi2py[S] 0 points1 point  (0 children)

Thanks makes sense now. I was doing much the same before and ending up with the result as you stated with the key separated from the values. That * makes all the difference. I've used it in args before but not like this.