Reorder a dictionary to fit a data frame

I have I dictionary in this format:

d = {'Name 1': list_of_links,'Name 2': list_of_links,'Name 3': list_of_links}

need to put this data in a DataFrame, with two columns:

Names and Links
Name 1    -> Link
Name 1    -> Link
...              ...
Name 2    -> Link
Name 2    -> Link
...             ....
Name 3    -> Link
Name 3    -> Link

I've try this:

links = []
names = []

for key in d:
    names.append(key)
    links.append(d[key])

and then to match the length

for i in range(len(names)):
    names[i] =[names[i]]*len(links[i])

And finally copy all the values in two new lists, but it doesn't seem like a good aproach

Upvotes: 0

Views: 70

Answers (2)

B. M.
B. M.

Reputation: 18668

Here , you can also build the DataFrame from tuples :

pd.DataFrame([(i,k)  for i in d.keys() for k in d[i]],columns=['names','links'])

Upvotes: 1

Stefan
Stefan

Reputation: 42905

Starting with a dict of two names and 10 different links each:

d = {'Name 1': ['link{}'.format(l) for l in list(range(10))], 'Name 2': ['link{}'.format(l) for l in list(range(10, 20))]}

{'Name 1': ['link0', 'link1', 'link2', 'link3', 'link4', 'link5', 'link6', 'link7', 'link8', 'link9'], 'Name 2': ['link10', 'link11', 'link12', 'link13', 'link14', 'link15', 'link16', 'link17', 'link18', 'link19']}

You could create a DataFrame .from_dict(), .stack(), and clean up the index:

df = pd.DataFrame.from_dict(d, orient='index').stack().reset_index(1, drop=True).to_frame().reset_index()
df.columns = ['name', 'link']

to get:

      name    link
0   Name 1   link0
1   Name 1   link1
2   Name 1   link2
3   Name 1   link3
4   Name 1   link4
5   Name 1   link5
6   Name 1   link6
7   Name 1   link7
8   Name 1   link8
9   Name 1   link9
10  Name 2  link10
11  Name 2  link11
12  Name 2  link12
13  Name 2  link13
14  Name 2  link14
15  Name 2  link15
16  Name 2  link16
17  Name 2  link17
18  Name 2  link18
19  Name 2  link19

Upvotes: 2

Related Questions