How do I convert a list of pairs into a dictionary with each element as a key to a list of paired values?

dictionary python
python dictionary value list append
write a python program to map two lists into a dictionary
python update dictionary value list
convert list to dictionary python
python print dictionary keys and values
how to store list in dictionary python
python dictionary add value to existing key

I'm doing coursework which involves graphs. I have edge lists E=[('a','b'),('a','c'),('a','d'), ('b','c') etc. ] and I want to a function to convert them into adjacency matrices in the form of dictionaries {'a':['b','c','d'], 'b':['a', etc. } so that I can use a function that only inputs these dictionaries.

My main issue is I can't figure out how to use a loop to add key:values without just overwriting the lists. A previous version of my function would output [] as all values because 'f' has no connections.

I've tried this:

V = ['a','b','c','d','e','f']
E=[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

def EdgeListtoAdjMat(V,E):
    GA={}
    conneclist=[]
    for v in V:
        for i in range(len(V)):
            conneclist.append([])
            if (v,V[i]) in E:
                conneclist[i].append(V[i])
    for i in range(len(V)):
        GA[V[i]]=conneclist[i]
    return(GA)

EdgeListtoAdjMat(V,E) outputs:

{'a': [], 'b': ['b'], 'c': ['c', 'c'], 'd': ['d', 'd', 'd'], 'e': [], 'f': []}

whereas it should output:

{'a':['b','c','d'],
'b':['a','c','d'],
'c':['a','b','d'],
'd':['a','b','c'],
'e':[],
'f':[]
}

The logic of what you're trying to achieve is actually quite simple:

V = ['a','b','c','d','e','f']
E=[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

result = {}
for elem in V:
     tempList = []
     for item in E:
          if elem in item:
               if elem == item[0]:
                    tempList.append(item[1])
               else:
                    tempList.append(item[0])
     result[elem] = tempList
     tempList = []

print(result)

Result:

{'a': ['b', 'c', 'd'], 'b': ['a', 'c', 'd'], 'c': ['a', 'b', 'd'], 'd': ['a', 'b', 'c'], 'e': [], 'f': []}

For every element in V, perform a check to see whether that element exists in any tuple in E. If it exists, then take the element that together form a pair on that tuple and append to a temporary list. After checking every element in E, update the result dictionary and move to the next element of V until you're done.

To get back to your code, you need to modify it as following:

def EdgeListtoAdjMat(V,E):
    GA={}
    conneclist=[]
    for i in range(len(V)):
        for j in range(len(V)):
            # Checking if a pair of two different elements exists in either format inside E. 
            if not i==j and ((V[i],V[j]) in E or (V[j],V[i]) in E):
                conneclist.append(V[j])
        GA[V[i]]=conneclist
        conneclist = []
    return(GA)

Python, Python – Convert Key-Value list Dictionary to List of Lists to perform the flattening a key value pair of dictionary to a list and convert to lists of list. In this, we loop through all the pairs and extract list value elements using� The basic method that can be applied to perform this task is the brute force method to achieve this. For this, simply declare a dictionary, and then run nested loop for both the lists and assign key and value pairs to from list values to dictionary.

A more efficient approach is to iterate through the edges and append to the output dict of lists the vertices in both directions. Use dict.setdefault to initialize each new key with a list. And when the iterations over the edges finish, iterate over the rest of the vertices that are not yet in the output dict to assign to them empty lists:

def EdgeListtoAdjMat(V,E):
    GA = {}
    for a, b in E:
        GA.setdefault(a, []).append(b)
        GA.setdefault(b, []).append(a)
    for v in V:
        if v not in GA:
            GA[v] = []
    return GA

so that given:

V = ['a', 'b', 'c', 'd', 'e', 'f']
E = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

EdgeListtoAdjMat(V, E)) would return:

{'a': ['b', 'c', 'd'], 'b': ['a', 'c', 'd'], 'c': ['a', 'b', 'd'], 'd': ['a', 'b', 'c'], 'e': [], 'f': []}

20. Dictionaries — How to Think Like a Computer Scientist: Learning , All of the compound data types we have studied in detail so far — strings, lists values, which can be any type (heterogeneous), just like the elements of a list or tuple. Another way to create a dictionary is to provide a list of key:value pairs using a view, which promises a list of tuples — one tuple for each key:value pair:. ''' Converting a list to dictionary with list elements as keys in dictionary using dict.fromkeys() ''' dictOfWords = dict.fromkeys(listOfStr , 1) dict.fromKeys() accepts a list and default value. It returns a dictionary with items in list as keys.

Since you already have your list of vertices in V, it is easy to prepare a dictionary with an empty list of connections. Then, simply go through the edge list and add to the array on each side:

V = ['a','b','c','d','e','f']
E = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

GA = {v:[] for v in V}
for v1,v2 in E:
    GA[v1].append(v2)
    GA[v2].append(v1)

How do you convert two lists into a dictionary?, By simply declaring a dictionary and then running a nested loop for both lists and assigning key:value pairs. Here one list elements are paired with the another list elements at corresponding index in key:value pair. Method #2 : Using defaultdict() + groupby() This method performs the task similar to above method, just instead of using loop to access each key value pair, here we use Python’s groupby library to group keys with value and convert then into a list.

I think your code is not very pythonic, you could write a more readable code that is simpler to debug and also faster since you are using python's built-in libraries and numpy's indexing.

def EdgeListToAdjMat(V, E):
    AdjMat = np.zeros((len(V), len(V)))  # the shape of Adjancy Matrix
    connectlist = {
        # Mapping each character to its index
        x: idx for idx, x in enumerate(V)
    }
    for e in E:
        v1, v2 = e
        idx_1, idx_2 = connectlist[v1], connectlist[v2]
        AdjMat[idx_1, idx_2] = 1     
        AdjMat[idx_2, idx_1] = 1

    return AdjMat

Using dictionaries to store data as key-value pairs, The Python list stores a collection of objects in an ordered sequence. pairs at once; Dictionaries and lists, compared; Insertion of elements dictionary objects and converting real-world data into dictionary objects. Oftentimes, we'd like to have access to both the key and the value for every key-value pair in a dictionary. A common dictionary is operation is to extract the values from the key: value pairs and convert them to a list, the code for which is actually quite straightforward. To see how it's done, check out the code snippet below.

If you'd consider using a library, networkx is designed for these type of network problems:

import networkx as nx 

V = ['a','b','c','d','e','f']
E = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

G=nx.Graph(E)
G.add_nodes_from(V)
GA = nx.to_dict_of_lists(G)

print(GA)

# {'a': ['c', 'b', 'd'], 'c': ['a', 'b', 'd'], 'b': ['a', 'c', 'd'], 'e': [], 'd': ['a', 'c', 'b'], 'f': []}

How to convert a dictionary into a list of tuples in Python, Converting a dictionary into a list of tuples creates a list that contains each key- value pair in the dictionary as a tuple. For example, converting the dictionary {"a": � To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Python : How to convert a list to dictionary ? – thispointer.com, Converting a list to dictionary with list elements as keys in dictionary Display contents of dictionary with each key/value pair in seperate line. To modify each key value pair before storing it in the list, you can use the list comprehension statement [ (k', v') for k, v in dict.items ()] replacing k' and v' with your specific modifications. In my code projects, I often find that choosing the right data structure is an important prerequisite to writing clean and effective code.

Python Dictionaries, and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. clear(), Removes all the elements from the dictionary. copy(), Returns a items(), Returns a list containing a tuple for each key value pair. dict = {k:v for k,v in (x.split(':') for x in list) } * If you want the conversion to int, you can replace k:v with int(k):int(v) ** Note: The general convention and advice is to avoid using map function, and instead use comprehension.

How to Convert Dictionary Values to a List in Python, how to convert dictionary data values from key: value pairs into a list quickly and You can create a dictionary easily within a pair of curly braces. See the code below for an example of what a dictionary looks like and how� In this tutorial, we will learn how to convert a dictionary into a list in Python with three different methods. A Dictionary is an unordered sequence that is mutable. Certainly, it is used for more flexible operations.