2

I have dict sample:

dictsample which have this structure dictsample.update({key: dif_k}), and dif_k have this structure dif_k.update({k:v})

dictsample:

{Object1 : { size : 14, cell: G, capacity : 35}, Object2 : { size : 14, load : 2}, Object3 : { size : 12, cell : F, load : 3, throughput : 55}, ...} 

I need output like this:

{Object1 : 3, Object2 : 2, Object3 : 4, ...}

Code I have tried:

ct = {}
for key, dif_k in dictsample.iteritems():
    for k, v in dif_k.iteritems():
        dictcounter = k.count(k)
        ct.update({key:dictcounter})

And all I got is: {Object1 : 1, Object2 : 1, Object3 : 1, ...}

3 Answers 3

3

Try something like this dict comprehension instead:

{k: len(v) for k,v in dictsample.iteritems()}
Sign up to request clarification or add additional context in comments.

1 Comment

This works great, but I got a problem when trying to transform to dataframe: If using all scalar values, you must pass an index I wanna df with just first columns with keys and second with counted values.
1

You can also do this:

the_list = {i:len(dictsample[i]) for i in dictsample.keys()}

this method does not require iteritems and is shorter.

Edit:

To access the values by a numerical element, try this:

the_list = {len(dictsample[i]):i for i in dictsample.keys()}

2 Comments

Thanks, but after that I have same problem with creating dataframe in pandas: If using all scalar values, you must pass an index I commented above... what do I need to put as an index? @Ajax1234
if you need a numerical index in the dictionary, just switch the dictionary key and values. Please see my recent edit.
1

Can't you do it a bit simpler. Wouldn't something like this do the trick?

ct = {}
for key in dictsample:
    ct[key] = len(dictsample[key])

2 Comments

You don't need dif_k.keys(). Python already iterates over dictionaries by key by default. So dif_k is sufficient.
This works great too, as an answer above, but I got the same problem.

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.