0

I have a dataframe with Nodes and Edges like this : Click to see the image of dataframe

I want to create of dictionnary of dictionnaries like this : dict = {125730: {268675130: 8.707, 4761621113: 132.800, 244455548 : 105.925, 60912980:130.717}, 8149548972: {8149548986: 4.439, 8149548986: 117.778}, 8149548979 etc....

but I don't find the solution... Can you help me ? Thank

  • As per the suggested duplicate, you could e.g. do: `my_dict = df.set_index('Edges').groupby('Nodes').apply(lambda x: x.Distance.to_dict()).to_dict()`. (Don't use `dict` as a variable to *store* a `dict`. Doing so will overwrite its built-in functionality.) – ouroboros1 Dec 11 '22 at 12:30

2 Answers2

0
import pandas as pd
df = pd.read_csv("test.csv")
df_dict = df.to_dict()
print(df_dict)
infinityPK
  • 53
  • 5
0

You can use:

dfx=df.groupby('Nodes').agg(list)

'''
|      Nodes | Edges                                          | Distance                       |
|-----------:|:-----------------------------------------------|:-------------------------------|
|     125730 | [268675130, 4761621113, 244455548, 1089076050] | [8707, 132800, 105925, 124290] |
|     125742 | [60912980]                                     | [130717]                       |
| 8149548972 | [8149548986, 8149548957]                       | [4439, 117778]                 |
| 8149548979 | [8149548986]                                   | [33505]                        |
| 8149548986 | [8112651374, 8149548979]                       | [44980, 33505]                 |
'''

Then combine Edges and Distance columns as a dictionary:

dfx['to_dict']=dfx.apply(lambda x: dict(zip(x['Edges'], x['Distance'])),axis=1)

'''
|      Nodes | to_dict                                                                      |
|-----------:|:-----------------------------------------------------------------------------|
|     125730 | {268675130: 8707, 4761621113: 132800, 244455548: 105925, 1089076050: 124290} |
|     125742 | {60912980: 130717}                                                           |
| 8149548972 | {8149548986: 4439, 8149548957: 117778}                                       |
| 8149548979 | {8149548986: 33505}                                                          |
| 8149548986 | {8112651374: 44980, 8149548979: 33505}                                       |
'''

Create dictionary with dfx.index and dfx['to_dict']:

final=dict(zip(dfx.index, dfx['to_dict']))

Output:

{
  "125730": {
    "244455548": 105925,
    "268675130": 8707,
    "1089076050": 124290,
    "4761621113": 132800
  },
  "125742": {
    "60912980": 130717
  },
  "8149548972": {
    "8149548986": 4439,
    "8149548957": 117778
  },
  "8149548979": {
    "8149548986": 33505
  },
  "8149548986": {
    "8112651374": 44980,
    "8149548979": 33505
  }
}
Bushmaster
  • 4,196
  • 3
  • 8
  • 28