hasmet
hasmet

Reputation: 778

How to use multidimensional dict in python

I'm trying to use a multidimensional dict in python. In my case, I need to use a structure like this:

MyDict[domain][IPAddress][UserAgent1, UserAgent2, UserAgent3, ....]

In this structure each key is a String and the last values are in a vector. I'm using this code for the first insertion:

from collections import defaultdict
MyDict= defaultdict(lambda: defaultdict(lambda: defaultdict(3)))

if domain not in MyDict:
    MyDict[domain] = [] 
if IPAddress not in MyDict[domain]:
    MyDict[domain].append(IPAddress)
if UserAgent1 not in MyDict[domain][IPAddress]:
    MyDict[domain][IPAddress].append(UserAgent1)

But this code doesn't work for this error:

Traceback (most recent call last):
  File "/.../Main.py", line 33, in <module>
    if UserAgent1 not in MyDict[domain][IPAddress]:
TypeError: list indices must be integers, not str

Additionally, I need to iterate on this structure. Do you know how to implement this structure and the best way to iterate on them?

Upvotes: 2

Views: 2353

Answers (1)

codebox
codebox

Reputation: 20254

The problem is that you have assigned a list to MyDict[domain] rather than a dictionary, try this instead:

if domain not in MyDict:
    MyDict[domain] = {}
if IPAddress not in MyDict[domain]:
    MyDict[domain][IPAddress] = []
if UserAgent1 not in MyDict[domain][IPAddress]:
    MyDict[domain][IPAddress].append(UserAgent1)

I'm not clear exactly what you want to see in the iteration, but this should get you started:

for domain in MyDict:
    for ipAddress in MyDict[domain]:
        for userAgent in MyDict[domain][ipAddress]:
            # code here will run for each combination of domain, ipAddress and userAgent

or the more 'Pythonic' version:

[[domain, ipAddress, userAgent] for domain in MyDict for ipAddress in MyDict[domain] for userAgent in MyDict[domain][ipAddress]]

Upvotes: 1

Related Questions