J.Do J.Do -4 years ago 119
Python Question

How to unpack into tuples the following nested list of dict?

I have a very large nested list like this one:

a_lis = [[{'A': 'the', 'B': 'US3---'}, {'A': 'the', 'B': 'PS3N'}, {'A': 'the', 'B': 'P3N'}, {'A': 'quick', 'B': 'GS'}, {'A': 'quick', 'B': 'NCMSN-'}, {'A': 'fox', 'B': 'YN-'}, {'A': 'it', 'B': 'VI--2PSA--N-'}, {'A': 'jumping', 'B': 'GNM-'}]]


How can to transform it into?:

[('the', 'US3---'), ('the', 'PS3N'), ('the', 'P3N'), ('quick', 'GS'), ('quick', 'NCMSN-'), ('fox', 'YN-'), ('it's, 'VI--2PSA--N-'), ('jumping', 'GNM-')]


I tried to:

tuples = ['{}'.join(x) for x in a_list[0]]


And:

values = [','.join(str(v) for v in a_list)]


The main issue is that I do not how to manage the
}{
characters. Could somebody explain which is the best way to manage them with a comprehension list?.

Answer Source

Fixing the syntax error with strings in your input line, you could the correct ensure order with something like

>>> list(map(lambda d: (d['A'], d['B']), a_lis[0]))

[('the', 'US3---'),
 ('the', 'PS3N'),
 ('the', 'P3N'),
 ('quick', 'GS'),
 ('quick', 'NCMSN-'),
 ('fox', 'YN-'),
 ("it's", 'VI--2PSA--N-'),
 ('jumping', 'GNM-')]

or equivalently with a list comprehension

>>> [(d['A'], d['B']) for d in a_lis[0]]

[('the', 'US3---'),
 ('the', 'PS3N'),
 ('the', 'P3N'),
 ('quick', 'GS'),
 ('quick', 'NCMSN-'),
 ('fox', 'YN-'),
 ("it's", 'VI--2PSA--N-'),
 ('jumping', 'GNM-')]

If a_lis had items beyond further lists beyond the first index you wanted to also have in the list of tuples, you could unpack.

list(map(lambda d: (d['A'], d['B']), *a_lis))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download