2

I would like to collect the installed packages and their versions of hosts to create a grid. The hosts don't necessarily have the same packages. For example:

enter image description here

In the first step I would like to simple store, and print these values. What data structure should I use?

I would like to store the data somehow liek this:

for .. 
  # read values
  versions[package][host] = version

I would like to print the values somehow like this:

for packagename in packagenames
  print packagename + ": "
  for host in hosts 
    if versions[host][package] is not None
      print versions[host][package]
    print ";"
  print "\n"

But because I don't know how many packages are there, and not all packages are exist in every host, I'm not sure how to do this. I guess I should use dictionary, but I'm don't know how.

BlackCat
  • 521
  • 3
  • 8
  • 22

3 Answers3

5

Using a defaultdict would be a good choice. You could fill your dictionary as shown in this example:

from collections import defaultdict

versions = defaultdict(dict)

versions["openssl"]["host1"] = "1.0.1e"
versions["openssl"]["host2"] = "1.0.1e"
...

By using a defaultdict, you can simply store your config using a loop, as you suggested.

from collections import defaultdict

versions = defaultdict(dict)
for .. 
    # read values
    versions[package][host] = version

Printing the dictionary can be a done like this:

for package, hosts in versions.items():
    print package + ": "
    for host, version in hosts:
        print host + ": " version 
    print "\n" 
miindlek
  • 3,523
  • 14
  • 25
0

Dict is best for storing these data:

     dict_data = {host:packagename for (host,packagename) in map(None, hosts, packagenames)}

Try this if this works.

Snehal Parmar
  • 5,453
  • 3
  • 35
  • 46
0

If you'd rather not use a defaultdict, this is how it would have been done before they were available:

pack_host = {}
for ...
    # read values
    pack_host.setdefault(package, {})[host] = version

the dictionary.setdefault(key,default) method is oddly-named. It actually gets the value for the first argument, like if you used dictionary[key], but if that key doesn't exist, it sets it to the default value and returns the value.

To print, you could do:

for package_name in pack_host:
    print package_name + ':',
    for host in pack_host[package_name]:
        print host,
    print
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172