Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary question
#5
(Nov-21-2020, 12:33 PM)kam_uk Wrote: can I not do this just using dictionary rather than a list of dictionary? I am specifically trying to learn about dictionaries here.

buran pointed out possibility: 'unless you want to make a more complex data structure'. You can have dictionary which value is dictionary as well. This way you can provide all the features with key, somthing along those lines:

>>> features = ['model', 'year', 'color']
>>> data = dict()
>>> data['Ford'] = dict(zip(features, ['Mustang', 2020, 'red']))
>>> data['Volvo'] = dict(zip(features, ['X90', 2020, 'white']))
>>> data
{'Ford': {'model': 'Mustang', 'year': 2020, 'color': 'red'}, 
 'Volvo': {'model': 'X90', 'year': 2020, 'color': 'white'}}
>>> data['Ford']['model']
'Mustang'
However, you probably see problem with that approach - you can have only one model per manufacturer as keys in dictionary must be unique. Therefore for similar records it is simpler to have list of dictionaries (or named tuples) and not introduce another layer of complexity to overcome key uniqueness requirement (value of key could be list of dictionaries for example where every model is one dictionary)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Dictionary question - by kam_uk - Nov-21-2020, 02:07 AM
RE: Dictionary question - by buran - Nov-21-2020, 07:26 AM
RE: Dictionary question - by kam_uk - Nov-21-2020, 12:33 PM
RE: Dictionary question - by perfringo - Nov-21-2020, 05:19 PM
RE: Dictionary question - by deanhystad - Nov-21-2020, 03:01 PM
RE: Dictionary question - by kam_uk - Nov-21-2020, 08:18 PM
RE: Dictionary question - by deanhystad - Nov-21-2020, 08:42 PM
RE: Dictionary question - by ndc85430 - Nov-22-2020, 05:43 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  dictionary question stereokim123 2 38,431 Apr-01-2021, 10:23 PM
Last Post: stereokim123

Forum Jump:

User Panel Messages

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