2

I'm trying to construct a nested dictionary from user inputs. The only issue is, the user can opt to not enter some of these inputs. In these cases, I want the dictionary to completely exclude that field. For Instance:

ids = 1234
dmas = 5678

I would like the dictionary to look like this:

d = {profile:{"dma_targets":dmas, "id":ids}}

However, if user decides not to include certain input:

ids = None
dmas = 5678

I would like the dictionary to look like this:

d = {profile:{"dma_targets":dmas}}

I'm a bit stuck here, and it seems like a very simple thing, as it would be easy to do if I wanted a list instead of a dict. One of the problems I'm running into is:

x = "dma_targets":dmas 

is not a valid object, so I'm having a hard time constructing the pieces of this, then adding them into the dictionary. Thanks so much!

David Yang
  • 2,101
  • 13
  • 28
  • 46
  • 1
    `x = "dma_targets":dmas` is not valid input, but `x = {"dma_targets":dmas}` is... why not try that? I guess I'm not totally clear what you're trying to achieve. If you can get it into a list, why not convert the list to a dict? http://stackoverflow.com/questions/4576115/python-list-to-dictionary – darthbith Oct 25 '13 at 14:22

3 Answers3

6

How about a little dict comprehension?

fkeys = ['dma_targets', 'ids']
fvals = [5678, None]
d = {'profile': {k:v for (k,v) in zip(fkeys, fvals) if v is not None}}

which yields d as

{'profile': {'dma_targets': 5678}}
ojdo
  • 8,280
  • 5
  • 37
  • 60
0
d = {profile:{}}
if ids:
    d['profile']['ids'] = ids
if dmas:
    d['profile']['dma_targets'] = dmas
Pablo Díaz Ogni
  • 1,033
  • 8
  • 12
0

If I understand correctly you want a nested dictionary with different types (python allows you to do this).

from collections import defaultdict
d  = defaultdict(lambda: defaultdict(list))
d['a']['b'].append('bla')
d[15] = 15
tk.
  • 626
  • 4
  • 14