[Tutor] Dict of Dict with lists

Alan Gauld alan.gauld at yahoo.co.uk
Wed Apr 25 13:35:30 EDT 2018


On 25/04/18 14:22, Kai Bojens wrote:

> The structure I'd like to have:
> 
> result = {
>         'foo at bar.de': {
>             'Countries': [DE,DK,UK]
>             'IP': ['192.168.1.1','172.10.10.10']
>             'Count': [12]
>             }
>         }
> ...
>     for line in logfile:
>         result = pattern.search(line)

Doesn't this overwrite your data structure?
I would strongly advise using another name.

>         if (result):
>             login_ip = result.group("login_ip")
>             login_auth =  result.group("login_auth")
>             response = reader.city(login_ip)
>             login_country = response.country.iso_code
>             if login_auth in result and login_country in result[login_auth]:
>                 continue
>             else:
>                 result[login_auth].append(login_country)
>         else:
>             continue

> 1. How do I check if a value exists within a list which is the value of a key 
> which is again a value of a key in my understanding exists? What I like to do:

dic = {'key1':{'key2':[...]}}

if my_value in dic[key1][key2]:

>  if login_auth in result and (login_country in result[login_auth][Countries])
>   continue

Should work.

> This obviously does not work and I am not quite sure how to address the values
> of 'Countries' in the right way. I'd like to check 'Key1:Key2:List' and don't
> know how to address this

It should worjk as you expect.
However personally I'd use a class to define tyour data structure and
just have a top leveldictionary holding instances of the class.
Something like:

class Login:
   def __init__(self, countries, IPs, count):
      self.countries = countries
      self.IPs = IPs
      self.count = count

results = {'foo at bar.de': Login([DE,DK,UK],
                               ['192.168.1.1','172.10.10.10'],
                               [12])
          }

if auth in results and (myvalue in results[auth].Countries):
   ...

BTW should count really be a list?

> 2. How do I append new values to these lists within the nested dict? 

Same as any other list, just use the append() method:

dic[key1][key2].append(value)

or with a class:

results[auth].IPs.append(value)


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list