简体   繁体   中英

How to create list of tuples from dictionary in python?

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)]

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], []))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM