Home > Software engineering >  How to create list of tuples from dictionary in python?
How to create list of tuples from dictionary in python?

Time:09-30

I have a dictionary and I want to create a list of tuples between tags. In fact, I want to make a connection between every 2 common tags that come in 2 different titles to draw a graph. How can I do this?

data = [
  {
    'title': 'title1', 'tags': ['tag1', 'tag2', 'tag3']
  },
  {
    'title': 'title2', 'tags': ['tag1','tag2']
  },
  {
    'title': 'title3', 'tags': ['tag2','tag3']
  }
]

what I want:

edge_list = [(tag1,tag2),(tag2,tag3)]

CodePudding user response:

one way is to create a function to iterate over the lists and get edges:

def get_edges_from_list(l):
    edges = []
    for i,x in enumerate(l[:-1]):
        edges.append((x, l[i 1]))
    return edges

then apply, flatten (with sum) and drop_duplicates (with set):

set(sum([get_edges_from_list(x['tags']) for x in data], []))
  • Related