Python Forum
Accessing nested dictionary values. Plistlib, Python 2.7
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Accessing nested dictionary values. Plistlib, Python 2.7
#21
Even when I try

for y in candidates2:
    for item2 in y["_items"]:
        if "size" in item2:
            HDsize = item2['size']
            print HDsize
nothing at all is outputted to the console.
Reply
#22
it is because
 
if "size" in item2:
is evaluated to False when there is no size in item2 and thus the body is not executed at all...
did you see my post, about using get method of the dict?
Reply
#23
I did try it but I was not sure at which 'level' of the for loop to apply it at.

There has to be a 'size' quality in the dictionary. When I search the plain-text output
of

for y in candidates2:
    for item in y['_items']:
        for item2 in item['_items']:
            print item2
            print ""
I can see " 'size': '500,11 GB'}]}" at the very end of the first dictionary (the one for internal hard drive). Ignore the double quotes.
Reply
#24
in your code, from post#16, just replace line#4 with my line. you have size for HDD, but if there is CD/DVD, you said that there is no size. That is the place in the script where you assign the value of HDsize by trying to retrieve the value of the key size from the dict. the error comes when there is no size key in the dict. dict.get(key, default_value) method supply second argument - the default one when the key is missing and there will be no error.
Reply
#25
OK. Thanks again for you help.

I've changed the code to your suggestion.

for y in candidates2:
    for item in y['_items']:
        for item2 in item['_items']:
            HDsize = item2.get("size", None)
            print HDsize
This will give me back

500,11 GB
None
When I try to run "print HDSize" completely outside of the loop, I only get "None". For simpler to retrieve values such as "serial_number" I don't have this problem. Is there anyway around this (even if it regarded as bad python practice)?

Is there anyway of making the loop work so that it only ever scans the first dictionary (the hard drive's) and ignores entirely the other dictionary?
Reply
#26
oh, would explain what do you want to do at the end. it gets frustrating like this...
it prints None if you print HDsize at the end because that is the last value from iterating...
eventually you want to write the values in a file, or store the values (while in the loop) in a dict to use them later....
Reply
#27
Sorry, I didn't think that having more than two dictionaries would complicate things so much.
Reply
#28
It doesn't.  It's just that you're also trying to ignore certain members of that dictionary while at the same time not ignoring them.  If you want your cake both ways, it gets complicated lol
Reply
#29
Yeah, a heartbreaker. I use the script with other python modules to paste data such as serial numbers, RAM, proc speed etc into another application. It's a bummer that certain machine types (those with two SATA drives) won't play with the script.
Reply
#30
I think I may have found some hackish way around this problem....


I found a "print_dict" function online on another forum last night.


def print_dict(v, prefix=''):
    if isinstance(v, dict):
        for k, v2 in v.items():
            p2 = "{}['{}']".format(prefix, k)
            print_dict(v2, p2)
    elif isinstance(v, list):
        for i, v2 in enumerate(v):
            p2 = "{}[{}]".format(prefix, i)
            print_dict(v2, p2)
    else:
        print('{} = {}'.format(prefix, repr(v)))
for y in candidates2:
    for item in y['_items']:
        for item2 in item['_items']:
            HDDetails = print_dict(item2)
            
the console outputs

['smart_status'] = 'Failing'
['detachable_drive'] = 'no'
['spsata_rotational_rate'] = 7200
['spsata_ncq_depth'] = '32'
['device_model'] = 'ST3500418ASQ                            '
['size_in_bytes'] = 500107862016
['_name'] = 'ST3500418ASQ'
... and so on
I can try saving the console output to a text file using sys.stdout and then later in the same script (outside the for loop) reopening the file and using string methods to chop it up and get the hard drive information I need.

I know the xml/plist data is no fun to read but I'm certain there is an easier way of getting access to this info?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need to compare 2 values in a nested dictionary jss 2 846 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Printing specific values out from a dictionary mcoliver88 6 1,368 Apr-12-2023, 08:10 PM
Last Post: deanhystad
  Accessing same python script from multiple computers bigrockcrasher 1 1,673 May-25-2022, 08:35 PM
Last Post: Gribouillis
  Python modules for accessing the configuration of relevant paths Imago 1 1,357 May-07-2022, 07:28 PM
Last Post: Larz60+
Question How to print each possible permutation in a dictionary that has arrays as values? noahverner1995 2 1,728 Dec-27-2021, 03:43 AM
Last Post: noahverner1995
  plistlib / xml file / get value except key Tecuma 6 3,204 May-26-2021, 03:51 PM
Last Post: Tecuma
  Nested dictionary acting strange Pedroski55 2 2,075 May-13-2021, 10:37 PM
Last Post: Pedroski55
  format the output from a nested dictionary. nostradamus64 9 4,509 May-03-2021, 04:45 PM
Last Post: nostradamus64
Lightbulb Python Nested Dictionary michaelserra 2 2,584 Apr-18-2021, 07:54 AM
Last Post: michaelserra
  Getting values from a dictionary brunolelli 5 3,543 Mar-31-2021, 11:57 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020