Parsing Python dictionary with multiple objects

Rustom Mody rustompmody at gmail.com
Tue Oct 14 22:32:27 EDT 2014


On Wednesday, October 15, 2014 7:35:18 AM UTC+5:30, Dave Angel wrote:
> anurag Wrote in message:
> > I have a dictionary that looks like this:
> > {"1":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, 
> > "2":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, 
> > "3":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, 
> > "4":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}}
> > Now if I have 100 objects like these and I need to split them into 3 smaller dicts in a ratio 2:3:5, how could I do that?
> > I tried using numpy.random.choice(), but it says it needs to be a 1-d array.


> What have you actually tried? You haven't shown any actual code.

> Look up the method dict.keys, and see how you might use that. Then
>  look up random.shuffle, and see what it would do. Also look up
>  dict.sort, since your two messages on this thread imply two
>  conflicting goals as to which sub dictionaries should go in which
>  of your buckets. 

> As for extracting 20% of the keys, slicing is your answer. If
>  there are 100 keys, 20, 30, and 50 need to be sliced
>  off.

> Then you'll need a loop to build each result dictionary from its keys.

> There are shortcuts,  but it's best to learn the fundamentals first.

> Try writing the code. If it doesn't all work show us what you've
>  tried, and what you think is wrong. And when you get an
>  exception, show the whole traceback,  don't just paraphrase one
>  of the lines.

Yes that is what is in general expected out here -- code --
maybe working, maybe not, maybe incomplete, maybe 'pseudo' etc
Then others here will improve it

However there is one conceptual thing that perhaps should be mentioned: order.

Is your data *essentially* ordered?

And by 'essentially' I mean you think of it independent of python.
Yeah in python dicts are unordered and lists are ordered and one can fudge
one to behave a bit like the other.  But before you fudge, please ponder which
you really need/want.

Below a bit of going from one to other 


# dict -> list
>>> d = {"a":1,"b":2,"c":3}
>>> d
{'a': 1, 'c': 3, 'b': 2}
>>> list(d)
['a', 'c', 'b']

# alternate
>>> d.keys()
['a', 'c', 'b']

>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> d.values()
[1, 3, 2]

# list -> dict
>>> dict(d.items())
{'a': 1, 'c': 3, 'b': 2}

# round-tripping
>>> dict(d.items()) == d
True



More information about the Python-list mailing list