Reputation: 41
this is my dictionary
dict = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}
i would like to get an output:
dictionary for a
apple: der Apfel
ant:die Ameise
asparagus:der Spargel
I am new to dictionaries please help
i tried doing
def tutorial8_part2():
dict = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}
dictList = dict.items()
for key, value in dict.iteritems():
temp = []
aKey = key
aValue = value
temp.append(aKey)
temp.append(aValue)
dictList.append(temp)
print dictList.append(temp)
but its not working
Upvotes: 2
Views: 176
Reputation: 2497
If you just want to print out each key and value pair in a long line, you can do this:
dict = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}
for key, value in dict.items():
print key + ':', value,
print
The output will probably not be in the same order as when you created the dictionary. Iterating through a dictionary doesn't guarantee any particular order, unless you specifically sort the keys, for example with the sorted() built-in function:
for key, value in sorted(dict_.items()):
print "{0}: {1}".format(key, value)
Upvotes: 3
Reputation: 143022
Will this do what you are trying to do?
(EDIT: updated to the new output format)
my_dict = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}
print 'dictionary for a'
for k, v in my_dict.iteritems():
print '%s:%s' % (k, v)
yields:
dictionary for a
ant:die Ameise
asparagus:der Spargel
apple:der Apfel
Note that this order is different from the one you posted, but the question didn't make it clear if order mattered.
As correctly suggested by @wim, it's better not to use dict
as a variable name.
Upvotes: 2
Reputation: 362736
If you are just trying to iterate through a dictionary, to print key and value pairs:
>>> dict_ = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}
>>> for k,v in dict_.iteritems():
... print k, ':', v
...
ant : die Ameise
asparagus : der Spargel
apple : der Apfel
In one-line using a generator expression:
>>> print '\n'.join('{}: {}'.format(k,v) for k,v in dict_.iteritems())
ant: die Ameise
asparagus: der Spargel
apple: der Apfel
As a side note, avoid using dict
as a variable name because it shadows the built-in.
Upvotes: 2