Python Forum
Why list(dict.keys()) does not work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why list(dict.keys()) does not work?
#6
A less elegant solution using nested dict that can be used with any python version:

item_dict = {
    '1': {
        'Item': 'Widgets',
        'Unit': 'each',
        'QtyPerUnit': 1,
        'PricePerUnit': 14.25
    },
    '2': {
        'Item': 'Wigs',
        'Color': ['red', 'brown', 'white'],
        'Unit': 'each',
        'QtyPerUnit': 1,
        'PricePerUnit': 5.25
    },
    '3': {
        'Item': 'fountain drink',
        'Size': ['small', 'medium', 'large'],
        'Unit': 'Ounces',
        'QtyPerUnit': 16,
        'PricePerUnit': 1.95
    }
}

merchandise = list(item_dict.keys())
merchandise.sort()
print('merchandise: {}'.format(merchandise))
print('item_dict 1: {}'.format(item_dict['1']))
results:
Output:
merchandise: ['1', '2', '3'] item_dict 1: {'PricePerUnit': 14.25, 'Item': 'Widgets', 'QtyPerUnit': 1, 'Unit': 'each'}
Reply


Messages In This Thread
RE: Why list(dict.keys()) does not work? - by wavic - Feb-02-2017, 07:55 AM
RE: Why list(dict.keys()) does not work? - by Larz60+ - Feb-02-2017, 05:52 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,368 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Beginner: Code not work when longer list raiviscoding 2 839 May-19-2023, 11:19 AM
Last Post: deanhystad
  How to work with list kafka_trial 8 2,059 Jan-24-2023, 01:30 PM
Last Post: jefsummers
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 1,232 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  Are list/dict comprehensions interpreted really sequentially? anata2047 3 1,469 May-31-2022, 08:43 PM
Last Post: Gribouillis
  Updating nested dict list keys tbaror 2 1,298 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Loop Dict with inconsistent Keys Personne 1 1,620 Feb-05-2022, 03:19 AM
Last Post: Larz60+
  Remove empty keys in a python list python_student 7 3,072 Jan-12-2022, 10:23 PM
Last Post: python_student
  Create Dict from multiple Lists with duplicate Keys rhat398 10 4,100 Jun-26-2021, 11:12 AM
Last Post: Larz60+
  Compile list of dictianories out of another list of dictianories by certain keys CatorCanulis 10 4,175 Jun-10-2021, 08:35 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

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