Parsing Python dictionary with multiple objects

MRAB python at
Wed Oct 15 00:58:25 CEST 2014

On 2014-10-14 22:15, Anurag Patibandla wrote:
> On Tuesday, October 14, 2014 12:59:27 PM UTC-4, Dave Angel wrote:
>> anuragpatibandla7 at 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 really have no idea what that means.  You have 100 dicts of
>>  dicts? Are the keys unique? If so, you could combine them with a
>>  loop of update.
>> > I tried using numpy.random.choice(), but it says it needs to be a 1-d array.
>> >
>> How about random.choice?  It needs a sequence.
>> To get anything more concrete, you need to specify Python version,
>> and make a clearer problem statement,  perhaps with example of
>> what you expect.
> Hey DaveA,
> I am using Python 2.7.
> Yes. I have a dict of dicts with keys ranging from 1..100
> And the value of each of these keys is another dict. What I need to do is make 3 smaller dicts and assign the values of keys 1..100 in the ratio 2:3:5.
> For example, if my original dict is
> d={"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"}}
>     ...
>     ...
>    "100":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}
> I need to have three dicts d1, d2, d3 with d1 containing the values of first 20 keys, d2 containing the values on next 30 keys and d3 containing the values of the next 50.
> Can you please help me with this?
You can get a list of the entries using the dict's .items method. It's
then a simple matter of slicing the list.

Note that dicts aren't ordered, i.e. its keys aren't in a fixed order,
so if you want then in a particular order, you'll need to sort the list.

More information about the Python-list mailing list