Playing with dictionaries

Discussion in 'Python' started by Roberto A. F. De Almeida, Sep 22, 2003.

  1. Hi,

    Suppose I have a dictionary containg nested dictionaries. Something
    like this:

    >>> pprint.pprint(dataset)

    {'casts': {'experimenter': None,
    'location': {'latitude': None,
    'longitude': None},
    'time': None,
    'xbt': {'depth': None,
    'temperature': None}},
    'catalog_number': None,
    'z': {'array': {'z': None},
    'maps': {'lat': None,
    'lon': None}}}

    I want to assign to the values in the dictionary the hierarchy of keys
    to it. For example:

    >>> dataset['casts']['experimenter'] = 'casts.experimenter'
    >>> dataset['z']['array']['z'] = 'z.array.z'


    Of course I would like to do this automatically, independent of the
    structure of the dictionary. Is there an easy way to do it?

    Thanks,

    Roberto
     
    Roberto A. F. De Almeida, Sep 22, 2003
    #1
    1. Advertising

  2. In article <>,
    (Roberto A. F. De Almeida) wrote:

    > Suppose I have a dictionary containg nested dictionaries. Something
    > like this:
    >
    > >>> pprint.pprint(dataset)

    > {'casts': {'experimenter': None,
    > 'location': {'latitude': None,
    > 'longitude': None},
    > 'time': None,
    > 'xbt': {'depth': None,
    > 'temperature': None}},
    > 'catalog_number': None,
    > 'z': {'array': {'z': None},
    > 'maps': {'lat': None,
    > 'lon': None}}}
    >
    > I want to assign to the values in the dictionary the hierarchy of keys
    > to it. For example:
    >
    > >>> dataset['casts']['experimenter'] = 'casts.experimenter'
    > >>> dataset['z']['array']['z'] = 'z.array.z'

    >
    > Of course I would like to do this automatically, independent of the
    > structure of the dictionary. Is there an easy way to do it?


    def makehierarchy(dataset,prefix=''):
    for key in dataset:
    if dataset[key] is None:
    dataset[key] = prefix + key
    elif isinstance(dataset[key], dict):
    makehierarchy(dataset[key], prefix + key + ".")
    else:
    raise ValueError, "Unexpected data type in makehierarchy"

    >>> makehierarchy(dataset,'dataset')
    >>> pprint.pprint(dataset)

    {'casts': {'experimenter': 'casts.experimenter',
    'location': {'latitude': 'casts.location.latitude',
    'longitude': 'casts.location.longitude'},
    'time': 'casts.time',
    'xbt': {'depth': 'casts.xbt.depth',
    'temperature': 'casts.xbt.temperature'}},
    'catalog_number': 'catalog_number',
    'z': {'array': {'z': 'z.array.z'},
    'maps': {'lat': 'z.maps.lat', 'lon': 'z.maps.lon'}}}

    --
    David Eppstein http://www.ics.uci.edu/~eppstein/
    Univ. of California, Irvine, School of Information & Computer Science
     
    David Eppstein, Sep 22, 2003
    #2
    1. Advertising

  3. [Roberto A. F. De Almeida]
    > Suppose I have a dictionary containg nested dictionaries. Something
    > like this:
    >
    > >>> pprint.pprint(dataset)

    > {'casts': {'experimenter': None,
    > 'location': {'latitude': None,
    > 'longitude': None},
    > 'time': None,
    > 'xbt': {'depth': None,
    > 'temperature': None}},
    > 'catalog_number': None,
    > 'z': {'array': {'z': None},
    > 'maps': {'lat': None,
    > 'lon': None}}}
    >
    > I want to assign to the values in the dictionary the hierarchy of keys
    > to it. For example:
    >
    > >>> dataset['casts']['experimenter'] = 'casts.experimenter'
    > >>> dataset['z']['array']['z'] = 'z.array.z'

    >
    > Of course I would like to do this automatically, independent of the
    > structure of the dictionary. Is there an easy way to do it?




    >>> def f(d):

    for k, v in d.iteritems():
    if v is None:
    yield k
    else:
    for name in f(v):
    yield k + '.' + name



    >>> list(f(d))

    ['casts.xbt.depth', 'casts.xbt.temperature', 'casts.experimenter',
    'casts.location.latitude', 'casts.location.longitude', 'casts.time',
    'z.maps.lat', 'z.maps.lon', 'z.array.z', 'catalog_number']


    Raymond Hettinger
     
    Raymond Hettinger, Sep 22, 2003
    #3
  4. In article <>,
    David Eppstein <> wrote:

    > def makehierarchy(dataset,prefix=''):
    > for key in dataset:
    > if dataset[key] is None:
    > dataset[key] = prefix + key
    > elif isinstance(dataset[key], dict):
    > makehierarchy(dataset[key], prefix + key + ".")
    > else:
    > raise ValueError, "Unexpected data type in makehierarchy"
    >
    > >>> makehierarchy(dataset,'dataset')


    Sorry, cut-and-paste error here -- updated the live code and forgot to
    update the copy in my posting. That should be makehierarchy(dataset).

    > >>> pprint.pprint(dataset)

    > {'casts': {'experimenter': 'casts.experimenter',
    > 'location': {'latitude': 'casts.location.latitude',
    > 'longitude': 'casts.location.longitude'},
    > 'time': 'casts.time',
    > 'xbt': {'depth': 'casts.xbt.depth',
    > 'temperature': 'casts.xbt.temperature'}},
    > 'catalog_number': 'catalog_number',
    > 'z': {'array': {'z': 'z.array.z'},
    > 'maps': {'lat': 'z.maps.lat', 'lon': 'z.maps.lon'}}}


    --
    David Eppstein http://www.ics.uci.edu/~eppstein/
    Univ. of California, Irvine, School of Information & Computer Science
     
    David Eppstein, Sep 22, 2003
    #4
  5. Roberto A. F. De Almeida

    Peter Otten Guest

    Roberto A. F. De Almeida wrote:

    > Suppose I have a dictionary containg nested dictionaries. Something
    > like this:
    >
    >>>> pprint.pprint(dataset)

    > {'casts': {'experimenter': None,
    > 'location': {'latitude': None,
    > 'longitude': None},
    > 'time': None,
    > 'xbt': {'depth': None,
    > 'temperature': None}},
    > 'catalog_number': None,
    > 'z': {'array': {'z': None},
    > 'maps': {'lat': None,
    > 'lon': None}}}
    >
    > I want to assign to the values in the dictionary the hierarchy of keys
    > to it. For example:
    >
    >>>> dataset['casts']['experimenter'] = 'casts.experimenter'
    >>>> dataset['z']['array']['z'] = 'z.array.z'

    >
    > Of course I would like to do this automatically, independent of the
    > structure of the dictionary. Is there an easy way to do it?


    class Dict:
    def __init__(self, name=None, parent=None):
    self.name = name
    self.parent = parent
    def __getitem__(self, name):
    return Dict(name, self)
    def __str__(self):
    if self.parent and self.parent.parent:
    return ".".join((str(self.parent), self.name))
    elif self.name is not None:
    return self.name
    return "I warned you"


    d = Dict()
    print d['casts']
    print d['casts']['experimenter']
    print d['casts']['location']['latitude']
    #print d # do not uncomment

    Seems to work :)
    I doubt that anybody can come up with something more automatic or more
    independent of the structure of the dictionary than the above. And it was
    easy, too, wasn't it?

    Peter
     
    Peter Otten, Sep 22, 2003
    #5
  6. Hi, guys.

    Thanks for the all the answers and the valuable insights. I mixed them
    all and got what I want. :)

    Roberto
     
    Roberto A. F. De Almeida, Sep 23, 2003
    #6
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ron Clarke

    Sound lost when playing AVI files

    Ron Clarke, Feb 24, 2004, in forum: ASP .Net
    Replies:
    0
    Views:
    351
    Ron Clarke
    Feb 24, 2004
  2. Trint Smith
    Replies:
    0
    Views:
    512
    Trint Smith
    Feb 27, 2004
  3. serkan ulucan
    Replies:
    3
    Views:
    572
    Smirnoff
    Apr 7, 2004
  4. lysdexia
    Replies:
    6
    Views:
    517
    John Machin
    Dec 2, 2007
  5. Brandon
    Replies:
    12
    Views:
    494
    Brandon
    Aug 15, 2008
Loading...

Share This Page