MuCh
MuCh

Reputation: 113

How to create a dictionary by iterating over a list, with same key multiple values?

I have the output from df command to check my filesystem. I got it from os.command and then added it to a list. Now I am realing line by line and want to create a dictionary as I need to send the response as a json later.

Filesystem          Size  Used Avail Use% Mounted on
/dev/xxxx/yyy       9.8G  3.2G  6.1G  35% /
tmpfs               32G     0   32G   0% /dev/shm
/dev/sss            247M  106M  129M  46% /boot
/dev/aaa/ccc        1.5G  205M  1.2G  15% /home
/dev/bbb/ddd        2.2G  152M  2.0G   8% /opt

How I want is:

{
Filesystem:/dev/xxxx/yyy
{ 
Size: 9.8G
Used:
Avail:
Use%:
Mounted on:
}
Filesystem:tmpfs
{ 
Size: 
Used:
Avail:
Use%:
Mounted on:
}
Filesystem:/dev/sss
{ 
Size: 
Used:
Avail:
Use%:
Mounted on:
}
}

My code as of now is :

output = os.popen('df -Ph')
df_contents=output.readlines()
for line in df_contents:
    print(line)

I want to understand if this is possible, since I have same key with different values and if so what is the best way to do this in python?

Upvotes: 2

Views: 92

Answers (3)

Bill M.
Bill M.

Reputation: 1548

To answer your question, no, you can't have different keys of the same name in the same dictionary. However, if you're grouping everything by FileSystem anyway, you could just have your dictionary's keys be the values themselves of FileSystem, in which case your dictionary will look like this:

{ '/dev/xxxx/yyy': {'Size': '9.8G', 'Used': '3.2G', ... }
  'tmpfs: {'Size': '32G', 'Used': '0', ... }
   ... and so on.
}

Assuming each line in df_contents has the data separated by whitespace (and not necessarily tabs), and there is no whitespace within any of the values themselves, then you can just use .split() to split each line.

var_keys = ['Size', 'Used', 'Avail', 'Use%', 'Mounted on']
mydict = {}
for line in df_contents:
    # This next command breaks the line into a list, 
    # like ['/dev/xxxx/yyy', '9.8G', '3.2G', '6.1G', '35%', '/']
    values = line.split()
    mydict[values[0]] = dict(zip(var_keys, values[1:]))

Upvotes: 1

kaihami
kaihami

Reputation: 815

Maybe you can go with compat and df.to_json

import pandas as pd
from pandas.compat import StringIO
df_contents = pd.read_csv(StringIO(output.read()), sep = '\t')
df_contents.to_json(orient='table')

Upvotes: 0

Kenan Banks
Kenan Banks

Reputation: 211980

Gonna be something pretty close to this:

headers = [
  'Size',
  'Used',
  'Avail',
  'Use%',
  'Mounted',
]

lines = [line.strip().split() for line in df_contents if line.strip()]

{line[0]: dict(zip(headers, line[1:])) for line in lines}

Upvotes: 0

Related Questions