# Dictionary of Dictionaries

**URL:** <https://forums.kodeco.com/t/dictionary-of-dictionaries/4367>\
**Category:** Swift\
**Created:** [March 2, 2016, 10:17am UTC](https://forums.kodeco.com/t/dictionary-of-dictionaries/4367 "2016-03-02T10:17:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![falsch](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/falsch/32/30431_2.png) [@falsch](https://forums.kodeco.com/u/falsch)\
**Post date:** [March 2, 2016, 10:17am UTC](https://forums.kodeco.com/t/dictionary-of-dictionaries/4367/1 "2016-03-02T10:17:07Z")

</div>

Hello,

I have a question regarding a Dictionary of Dictionaries. Is there a shorter way to put single elements in the Dict than I did?

```
var cellHeight = [Int : [ Int : CGFloat] ]()

// ...

if let _ = cellHeight[0] {
    cellHeight[0]![2] = 0.0
} else {
    cellHeight[0] = [2 : 0.0]
}

```

In all the tutorials I checked it’s only explained how to fill/initialize the full dict-of-dict and than read from it, but not how to fill it part by part.

Thanx

alex

---

<div class="post-metadata">

**Author:** ![marciokoko](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/marciokoko/32/32922_2.png) [@marciokoko](https://forums.kodeco.com/u/marciokoko)\
**Post date:** [March 2, 2016, 9:50pm UTC](https://forums.kodeco.com/t/dictionary-of-dictionaries/4367/2 "2016-03-02T21:50:24Z")

</div>

Do you wish to fill a dictionary of dictionaries with automatically in the sense that you want to one-time-migrate data to the structure?

Or do you wish to capture user data in some way and put it into a dictionary-of-dictionaries?

---

<div class="post-metadata">

**Author:** ![jcatterwaul](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/jcatterwaul/32/94210_2.png) [@jcatterwaul](https://forums.kodeco.com/u/jcatterwaul)\
**Post date:** [March 4, 2016, 6:42pm UTC](https://forums.kodeco.com/t/dictionary-of-dictionaries/4367/3 "2016-03-04T18:42:49Z")

</div>

I don’t think there’s a built-in way to do what you did, better than you did. How about this?

```swift
public extension Dictionary {
	subscript(
		key: Key,
		@autoclosure valueAddedIfNil Value: () -> Dictionary.Value
	) -> Dictionary.Value {
		mutating get {
			return self[key] ?? {
				self[key] = Value()
				return self[key]!
			}()
		}
		set {self[key] = newValue}
	}
}

```

```swift
cellHeight[0, valueAddedIfNil: [:]][2] = 0

```
