Home > OS >  How to make tuple with list of dictionary inpython?
How to make tuple with list of dictionary inpython?

Time:10-21

I have a list of dictionary and I want to make tuple from tags value, So that the tags in an array are placed in pairs. How can I do this:

output: [
        {
          "title": "subject1",
          "tags": ['a','b'],
 },
        {
          "title": "subject2",
          "tags": ['c','d','f'],
 }]

what I want:

[(a,b),(c,d),(c,f),(d,f)]

CodePudding user response:

You can use itertools.combinations() to get it. The following will work

from itertools import combinations

L1 = [{"title": "subject1", "tags": ['a','b']},
      {"title": "subject2", "tags": ['c','d','f']}]

res = []

for i in L1:
    tags = combinations(i["tags"], 2)
    res  = list(tags)

print(res)

CodePudding user response:

You can use itertools.combinations(... , 2) and itertools.chain and get what you want like below:

>>> import itertools

>>> results = [{"title": "subject1","tags": ['a','b'],},{"title": "subject2","tags": ['c','d','f'],}]

>>> lst = [list(itertools.combinations(res['tags'] , 2)) for res in results]
>>> lst
[[('a', 'b')], [('c', 'd'), ('c', 'f'), ('d', 'f')]]

>>> list(itertools.chain.from_iterable(lst))
[('a', 'b'), ('c', 'd'), ('c', 'f'), ('d', 'f')]

Or without chain:

>>> import itertools
>>> results = [{"title": "subject1","tags": ['a','b'],},{"title": "subject2","tags": ['c','d','f'],}]
>>> out = []
>>> for res in results:
...    out  = list(itertools.combinations(res['tags'] , 2))
>>> out
[('a', 'b'), ('c', 'd'), ('c', 'f'), ('d', 'f')]

# for more explanation
[1,2] [3,4]
[1,2,3,4]
  • Related