1

I have a dictionary like so:

d = {'3a0fe308-b78d-4080-a68b-84fdcbf5411e': 'SUCCEEDED-HALL-IC_GBI', '7c975c26-f9fc-4579-822d-a1042b82cb17': 'SUCCEEDED-AEN-IC_GBI', '9ff20206-a841-4dbf-a736-a35fcec604f3': 'SUCCEEDED-ESP2-IC_GBI'}

I would like to convert my dictionary into something like this to make a dataframe where I put all the keys and values in a separate list.

d = {'key': ['3a0fe308-b78d-4080-a68b-84fdcbf5411e', '7c975c26-f9fc-4579-822d-a1042b82cb17', '9ff20206-a841-4dbf-a736-a35fcec604f3'],
     'value': ['SUCCEEDED-HALL-IC_GBI', 'SUCCEEDED-AEN-IC_GBI', 'SUCCEEDED-ESP2-IC_GBI']

What would be the best way to go about this?

3 Answers 3

3

You can easily create a DataFrame like this:

import pandas as pd

d = {'3a0fe308-b78d-4080-a68b-84fdcbf5411e': 'SUCCEEDED-HALL-IC_GBI',
     '7c975c26-f9fc-4579-822d-a1042b82cb17': 'SUCCEEDED-AEN-IC_GBI',
     '9ff20206-a841-4dbf-a736-a35fcec604f3': 'SUCCEEDED-ESP2-IC_GBI'}
table = pd.DataFrame(d.items(), columns=['key', 'value'])

If you just want to rearrange your Dictionary you could do this:

d2 = {'key': list(d.keys()), 'value': list(d.values())}
Sign up to request clarification or add additional context in comments.

1 Comment

This use of items() to pass in keys and values as individual columns was just what I was looking for. Not obvious; very clever. Thanks!
1

Since you tagged pandas, try:

pd.Series(d).reset_index(name='value').to_dict('list')

Output:

{'index': ['3a0fe308-b78d-4080-a68b-84fdcbf5411e',
  '7c975c26-f9fc-4579-822d-a1042b82cb17',
  '9ff20206-a841-4dbf-a736-a35fcec604f3'],
 'value': ['SUCCEEDED-HALL-IC_GBI',
  'SUCCEEDED-AEN-IC_GBI',
  'SUCCEEDED-ESP2-IC_GBI']}

Pure python:

{'key':list(d.keys()), 'value': list(d.values())}

output:

{'key': ['3a0fe308-b78d-4080-a68b-84fdcbf5411e',
  '7c975c26-f9fc-4579-822d-a1042b82cb17',
  '9ff20206-a841-4dbf-a736-a35fcec604f3'],
 'value': ['SUCCEEDED-HALL-IC_GBI',
  'SUCCEEDED-AEN-IC_GBI',
  'SUCCEEDED-ESP2-IC_GBI']}

Comments

1

You can create the dataframe zipping the key/value lists with zip function:

import pandas as pd

df = pd.DataFrame(list(zip(d.keys(),d.values())), columns=['key','value'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.