Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Nested dictionary issue
#1
Hi all,

I am struggling a bit with some code and would really appreciate some guidance.

I currently have the below input dictionary
Quote:[OrderedDict([('@id', '1'), ('@state', 'IDLE')]), OrderedDict([('@id', '2'), ('@state', 'IDLE')])]
OrderedDict([('@id', '1'), ('@state', 'HIGH')])
[OrderedDict([('@id', '21'), ('@state', 'HIGH')]), OrderedDict([('@id', '22'), ('@state', 'IDLE')])]

And would like to get something like that as an output :
Quote:['IDLE',1,2,22]['HIGH',1,21]

My current code after many try is :
                        print(ZD['Status']['Zone'])
                        ret = OrderedDict()
                        for key, value in ZD['Status']['Zone']:
                            print('***')
                            print(key, value)
                            if value not in ret:
                                ret[value] = []
                                ret[value].append(key)

                        print ([[value] + key for value, key in ret.items()])
and the current output :
Quote:***
@id @state
[['@state', '@id']]
Any advice would be really appreciated
Reply
#2
please express dictionaries as python code
Reply
#3
If you want to iterate over the key/value pairs of a dictionary, you need to use items: for key, value in ZD['Status']['Zone'].items():.

Also, you need to un-indent your append on line 8. As it is you are only appending the first item, not any later ones.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
Thanks, this helped. I used another method to achieve this and this seems to work now.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need to compare 2 values in a nested dictionary jss 2 855 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Nested dictionary acting strange Pedroski55 2 2,085 May-13-2021, 10:37 PM
Last Post: Pedroski55
  format the output from a nested dictionary. nostradamus64 9 4,530 May-03-2021, 04:45 PM
Last Post: nostradamus64
Lightbulb Python Nested Dictionary michaelserra 2 2,594 Apr-18-2021, 07:54 AM
Last Post: michaelserra
  Issue accessing data from Dictionary/List in the right format LuisSatch 2 2,206 Jul-25-2020, 06:12 AM
Last Post: LuisSatch
  nested dictionary rkpython 7 3,257 May-29-2020, 11:13 AM
Last Post: rkpython
  Nested Dictionary/List tonybrown3 5 3,150 May-08-2020, 01:27 AM
Last Post: tonybrown3
  Help: for loop with dictionary and nested lists mart79 1 1,864 Apr-12-2020, 02:52 PM
Last Post: TomToad
  Transforming nested key-tuples into their dictionary values ClassicalSoul 4 2,658 Apr-11-2020, 04:36 PM
Last Post: bowlofred
  How to change value in a nested dictionary? nzcan 2 5,763 Sep-23-2019, 04:09 PM
Last Post: nzcan

Forum Jump:

User Panel Messages

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