0

I need to create array/dictionaries in python based on an array which contains keys. I found an equivalent solution in PHP. Unfortunately I don't know how I can implement this in Python. Can somebdoy give me any tips?

a = ['one', 'two', 'three']
b = ['one', 'four', 'six']

I want to get the following result:

c = {'one': {'two': 'three', 'four': 'six}}

The PHP solution uses references for that. Perhaps this is a better example:

ar[0] = ['box0', 'border0', 'name']
var[1] = ['box0', 'border0', 'type']
var[2] = ['box0', 'border1', 'name']
var[3] = ['box1', 'border2', 'name']
var[4] = ['box1', 'border0', 'color']

$val = 'value'

In PHP the result would look like:

$result = array(
    'box0' => array(
      'border0' => array('name' => $val, 'type' => $val, 'color' => $val), 
      'border1' => array('name' => $val),
    ),
    'box1' => array(
      'border0' => array('color' => $val),
      'border2' => array('name' => $val)
    )
) );
Community
  • 1
  • 1
user1119698
  • 157
  • 2
  • 15
  • Is this strictly for the case of 3-tuples of key, subkey, and value, or are you trying to generalize this to lists of length N? – Joel Cornett Mar 10 '13 at 16:47
  • related: [Python: Change values in dict of nested dicts using items in a list](http://stackoverflow.com/questions/11918852/python-change-values-in-dict-of-nested-dicts-using-items-in-a-list) – jfs Mar 10 '13 at 17:14
  • It is possible to N-tuples of key. This is only an example. – user1119698 Mar 10 '13 at 18:14

2 Answers2

2

The PHP answer constructs a dictionary from a path of keys. So here's an equivalent in Python:

from collections import defaultdict
def set_with_path(d, path, val):
    end = path.pop()
    for k in path:
        d = d.setdefault(k, {})
    d[end] = val

Example:

>>> d = {}
>>> set_with_path(d, ['one', 'two', 'three'], 'val')
>>> d
{'one': {'two': {'three': 'val'}}}
>>> set_with_path(d, ['one', 'four', 'six'], 'val2')
>>> d
{'one': {'four': {'six': 'val2'}, 'two': {'three': 'val'}}}
nneonneo
  • 171,345
  • 36
  • 312
  • 383
0
x = dict()
for list in (a,b):
    if not x.has_key(list[0]):
        x[list[0]] = []
    x[list[0]] += list[1:]
Eric Urban
  • 3,671
  • 1
  • 18
  • 23