Hyungsoo Kim
Hyungsoo Kim

Reputation: 39

how to search and print dictionary with python?

for example, I have a dictionary like this

print(fruitdict)
defaultdict(<class 'set'>, {'apple':{'red'}, 'banana':{'yellow'}, 'cinnamon':{'brown'}...
etc

order is not a problem, I just want to print like

"apple have red color."
"banana have yellow color."
"cinammon have brown color."
etc

I don't have any idea, because I thought just

x = len(fruitdict)
for n = range(0, x+1):
    print(fruitdict.keys()[n])
    print(" have ")
    print(fruitdict.item()[n])
    print(" color.")

of course, it didn't work. how can I pickup the key and items in dictionary?

Upvotes: 0

Views: 340

Answers (4)

Zoro_77
Zoro_77

Reputation: 415

Consider using the pprint module. It will do the job with much cleaner output and indent.

import pprint                                                                       
pp = pprint.PrettyPrinter(indent=4)                                     
pp.pprint(dictobj)       

Upvotes: -1

halex
halex

Reputation: 16403

You can do it with the following code

for fruit, colors in fruitdict.items():
    print('{} have {} color.'.format(fruit, ' '.join(colors)))

Upvotes: 3

ZdaR
ZdaR

Reputation: 22954

fruitdict = {'apple':{'red'}, 'banana':{'yellow'}, 'cinnamon':{'brown'}}

for key in fruitdict:
    print key + " have " + str(list(fruitdict[key])[0]) + " color."

Upvotes: -2

Cory Kramer
Cory Kramer

Reputation: 117951

If instead of a defaultdict you just had a normal dictionary

d = {'apple':'red', 'banana':'yellow', 'cinnamon':'brown'}

You could iterate of the items and use format to create a string

for (key, value) in d.items():
    print('{} have {} color.'.format(key, value))

Output

cinnamon have brown color.
apple have red color.
banana have yellow color.

Upvotes: 1

Related Questions