Python Forum
Dictionary multi dimension support
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary multi dimension support
#4
you can use dict.setdefault() method
d = {}
d.setdefault('key1', {})['key2'] = 'foo'
print(d)
d.setdefault('key1', {})['key3'] = 'bar'
print(d)
Output:
{'key1': {'key2': 'foo'}} {'key1': {'key3': 'bar', 'key2': 'foo'}}
another option is to use defaultdict from collections

from collections import defaultdict
d = defaultdict(dict)
d['key1']['key2'] = 'foo'
print(d)
d['key1']['key3'] = 'bar'
print(d)
Output:
defaultdict(<class 'dict'>, {'key1': {'key2': 'foo'}}) defaultdict(<class 'dict'>, {'key1': {'key2': 'foo', 'key3': 'bar'}})
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
Dictionary multi dimension support - by sripylearn - Aug-14-2018, 03:14 PM
RE: Dictionary multi dimension support - by Vysero - Aug-14-2018, 03:25 PM
RE: Dictionary multi dimension support - by Larz60+ - Aug-14-2018, 03:28 PM
RE: Dictionary multi dimension support - by buran - Aug-14-2018, 03:50 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Array dimension don't match asja2010 0 1,087 Feb-23-2023, 04:22 PM
Last Post: asja2010
  x and y must have same first dimension, but have shapes (1,) and (50,) asja2010 5 2,635 Jan-12-2023, 07:24 PM
Last Post: deanhystad
  Strange error ValueError: dimension mismatch Anldra12 0 1,982 Aug-17-2021, 07:54 AM
Last Post: Anldra12
  ValueError: dimension mismatch Anldra12 0 3,411 Jul-17-2021, 04:46 PM
Last Post: Anldra12
  ValueError: x and y must have same first dimension, but have shapes (11,) and (15406, hobbyist 17 150,757 Mar-22-2021, 10:27 AM
Last Post: hobbyist
  Error When Plotting ValueError: x and y must have same first dimension JoeDainton123 1 9,114 Oct-04-2020, 12:58 PM
Last Post: scidam
  Wrong dimension for my plot Jemeronimo 1 2,029 Apr-25-2019, 06:19 PM
Last Post: Larz60+
  Fast method of searching a string in a multi-dimension array? draems 6 5,983 Feb-20-2017, 01:02 PM
Last Post: Ofnuts
  Build a multi-variable dictionary birdieman 4 5,031 Jan-06-2017, 04:34 PM
Last Post: birdieman

Forum Jump:

User Panel Messages

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