user15365664
user15365664

Reputation:

How can I get the key value pair to create a dictionary from a nested dictionary?

I have a dictionary which looks as shown below. Now I need to get the key its corresponding path together so as to use it further to identify its slot number based on the key. How can I achieve that? I tried an approach but it is giving me key error.

Upvotes: 1

Views: 77

Answers (2)

sxddhxrthx
sxddhxrthx

Reputation: 794

Great one line answer by @Selcuk using dictionary comprehension.

An elaborated one along the same line would be:

mpath_dict = {}

for sd, mpath in multipath.items():
    mpath_dict[sd] = mpath['mpath']

print(mpath_dict)

Since every value item of "mpath" dictionary is a dictionary itself, you can retrieve values from it as you would do it in a dictionary.

Upvotes: 0

Selcuk
Selcuk

Reputation: 59184

What you need can easily be implemented as:

>>> {key: value["mpath"] for key, value in multipath.items()}
{'/dev/sdh': '/dev/mapper/mpathk', '/dev/sdi': '/dev/mapper/mpathk',
 '/dev/sdg': '/dev/mapper/mpathj', '/dev/sdf': '/dev/mapper/mpathj',
 '/dev/sdd': '/dev/mapper/mpathi', '/dev/sde': '/dev/mapper/mpathi',
 '/dev/sdb': '/dev/mapper/mpathh', '/dev/sdc': '/dev/mapper/mpathh',
 '/dev/sdj': '/dev/mapper/mpathg', '/dev/sdk': '/dev/mapper/mpathg'}

Upvotes: 2

Related Questions