python - Entries in Nested Dictionaries -


given nested dictionary:

mydict = { 'through': { 1: 18,                         2: 27,                         3:  2,                         4: 15,                         5: 63                         },            'one':     { 1: 27,                         2: 15,                         3: 24,                         4:  9,                         5: 32                         },            'clock':   { 1:  2,                         2:  5,                         3:  9,                         4:  6,                         5: 15                         }            } 

the outer key word, inner keys files that word contains , values number of times said word appears in file.

how use file numbers work out total number of text files present?

i.e. is there way of extracting number of key / value pairs in inner dictionary?

i.e. numoffiles = 5

because there 5 files here, had hundreds , read dictionary automatically, had work out?

len function calculate length:

>>>len(mydict['through']) 5 

if want word , how many files contains it: can use dictionary comprehension

>>>{ x:len(y) x,y in mydict.items() } {'one': 5, 'through': 5, 'clock': 5} 

you asked key/value pair:

 >>> [ y.items() x,y in mydict.items() ] [[(1, 2), (2, 5), (3, 9), (4, 6), (5, 15)], [(1, 18), (2, 27), (3, 2), (4, 15), (5, 63)], [(1, 27), (2, 15), (3, 24), (4, 9), (5, 32)]] 

itemsgives tuple of key/value pair inner dictionary

if word not present infile, check greater 0:

>>> mydict {'clock': {1: 2, 2: 5, 3: 9, 4: 6, 5: 15}, 'through': {1: 18, 2: 27, 3: 2, 4: 15, 5: 63}, 'one': {1: 27, 2: 15, 3: 0, 4: 9, 5: 32}} >>>{ x:len(filter(lambda x:x if x > 0 else false,y.values())) x,y in mydict.items() } {'one': 4, 'through': 5, 'clock': 5} 

here 1 not present in file 3


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -