Selecting items in a dictionary using python -
my goal first select first 3 items in dictionary below. select items values greater 1.
dic=counter({'school': 4, 'boy': 3, 'old': 3, 'the': 1}) attempt: 1.>>> {x:x x in dic if x[1]>1} {'boy': 'boy', 'the': 'the', 'old': 'old', 'school': 'school'} 2.>>>dic[:3] typeerror: unhashable type desired output: counter({'school': 4, 'boy': 3, 'old': 3})
thanks suggestions.
for items count greater one:
>>> [x x in dic if dic[x] > 1] ['boy', 'school', 'old']
for 3 most common items:
>>> [x x, freq in dic.most_common(3)] ['school', 'boy', 'old']
to dictionaries:
>>> {x: freq x,freq in dic.items() if freq > 1} {'boy': 3, 'school': 4, 'old': 3} >>> {x: freq x,freq in dic.most_common(3)} {'boy': 3, 'school': 4, 'old': 3}
note: ordinary dictionaries. utilize counter(result)
turn them counter
s. alternatively dictionary comprehension can utilize builtin dict
function turn list of tuples dictionary, , create counter
that.
>>> counter(dict(dic.most_common(3))) counter({'school': 4, 'boy': 3, 'old': 3})
python dictionary
No comments:
Post a Comment