Home > Blockchain >  Transform dictionary key-value pairs to list of tuples
Transform dictionary key-value pairs to list of tuples

Time:03-03

I have a dictionary of lists:

dic = {'contig_100003': ['contig_14576'],  'contig_100022': ['contig_96468'],  'contig_100023': ['contig_24939', 'contig_33444', 'contig_72441']}

And I would like to get a list (including the key) of it:

List = [(contig_100003','contig_14576'), (contig_100022','contig_96468'), (contig_100023','contig_24939', 'contig_33444', 'contig_72441')]

However, my code cannot get rid of the internal/value list:

list(dic.items())
[('contig_100003', ['contig_14576']),
 ('contig_100022', ['contig_96468']),
 ('contig_100023', ['contig_24939', 'contig_33444', 'contig_72441'])]

CodePudding user response:

This might solve it

[(k, *v) for k, v in dic.items()]

CodePudding user response:

You can use tuple concatenation to get the desired output:

result = [(key,)   tuple(value) for key, value in dic.items()]
print(result)

This outputs:

[('contig_100003', 'contig_14576'), ('contig_100022', 'contig_96468'),
('contig_100023', 'contig_24939', 'contig_33444', 'contig_72441')]
  • Related