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)
    )
) );
3
  • 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? Commented Mar 10, 2013 at 16:47
  • related: Python: Change values in dict of nested dicts using items in a list Commented Mar 10, 2013 at 17:14
  • It is possible to N-tuples of key. This is only an example. Commented Mar 10, 2013 at 18:14

2 Answers 2

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'}}}
Sign up to request clarification or add additional context in comments.

Comments

0
x = dict()
for list in (a,b):
    if not x.has_key(list[0]):
        x[list[0]] = []
    x[list[0]] += list[1:]

2 Comments

That will produce {'one': ['two', 'three', 'four', 'six']} instead.
The phrasing of the question let me to believe he wanted a dictionary of lists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.