Search code examples
pythongraphnetworkxtheory

Create a graph of authors as edge list from paired dictionary keys in python


I am trying to create an adjacency list in python for coauthorship graph. I have created a dictionary pf author

{'a1': ' A-ming Hao',
 'a2': ' Qing-zhen Wang',
 'a3': ' Xiao-long Li',
 'a4': ' Ming-da Zhai'}

I have created edge in this way.

g=nx.Graph()    

g.add_edge(y[0]['a1'],y[0]['a2'])
g.add_edge(y[0]['a2'],y[0]['a3'])
g.add_edge(y[0]['a3'],y[0]['a4'])
g.add_edge(y[0]['a4'],y[0]['a1'])

but I want to do it using for loop

for key,val in (y[0].items()):
    g.add_edge(y[0][key],y[0][key])

I want this loop to iterate through each key. and create edge like this

g.add_edge(y[0][key],y[0][key+1])

so that an edge can be created between key[a1] and key[a2],. in my for loop it is actually an edge between key[a1] and key[a1].

and when it reach to last key[a4] connect it first key[a1]

any idea?


Solution

  • You can use list slicing on the dict.keys() in combination with zip() to get your tuples to put into your graph:

    authors = {'a1': ' A-ming Hao',
               'a2': ' Qing-zhen Wang',
               'a3': ' Xiao-long Li',
               'a4': ' Ming-da Zhai'}
    
    keys = list(authors .keys())
    
    # zip keys with itself - rotated by 1 element
    tups = list(zip(keys, keys[1:]+keys[0:1]))
    
    print(tups)
    

    Output:

    [('a1', 'a2'), ('a2', 'a3'), ('a3', 'a4'), ('a4', 'a1')]
    

    with those tuples you can do:

    g = nx.Graph()
    for a,b in tups:
        g.add_edge(authors[a], authors[b])
    

    You should keep in mind that the order in which keys are presented might vary - if you need to ensure insertion order you need to use:

    • python 3.7 up guarantees insertion order on dicts
    • CPython 3.6 up has insertion order by implementation detail/sideeffect
    • or use an OrderedDict

    to begin with ( or use keys = sorted(d.keys()) )


    For dict insertion order, read information @ Are dictionaries ordered in Python 3.6+?