For an input nested list
[[[1, 2], [3, 4]], [[5,6]], [[7,8], [9,10], [10,10]]]
I want to build a comprehension that will assemble a nested dictionary D such that:
D[0] [1] = 2, D[0][3] = 4
D[1] [5] = 6
D[2] [7] = 8, D[2][9] = 10, D[2][10] = 10
My dictionary comprehension is the following:
dict = {k1:{v[0]:v[1]} for k1, sub in enumerate(tg1) for v in sub}
but there is a problem in that it does not contain every pair.
How do I do this?
If you want to use dictionary comprehension, you have to nest it. In your approach only one key-value pair gets to your inner dictionary, wherein you actually want that part to be a comprehension itself. Something like this would work:
d = {i:{k:v for k,v in sublist} for i, sublist in enumerate(l)}
Assuming l
is your list here.
If you only have these levels of nesting, you can do it with a comprehension. On the other hand if you have more levels, you'll probably need a (recursive) function:
D = { i:dict(L) for i,L in enumerate(yourList)}
{0: {1: 2, 3: 4},
1: {5: 6},
2: {7: 8, 9: 10, 10: 10}}
D[0][3] # 4
D[1][5] # 6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.