Reputation: 3851
I have a dictionary for which key is a normal string and value is a tuple for which example is shown below:
'Europe':(Germany, France, Italy)
'Asia':(India, China, Malaysia)
I want to display the dictionary items like this:
'Europe':(RandomStringA:Germany, RandomStringB:France, RandomStringC:Italy)
'Asia':(RandomStringA:India, RandomStringB:China, RandomStringC:Malaysia)
I tried the code below:
for k, v in dict.iteritems()
print k, "Country1":v[0], "Country2":v[1], "Country3":v[2]
But this does not seem to work. Is there a way to tag items in a tuple like that? Thanks in advance!
Upvotes: 0
Views: 72
Reputation: 11026
If you're just trying to print that:
for k, v in dct.iteritems():
print repr(k)+ ":(" + ", ".join("Country{}:{}".format(i,c) for i,c in enumerate(v, start=1)) + ")"
Output:
'Europe':(Country1:Germany, Country2:France, Country3:Italy)
'Asia':(Country1:India, Country2:China, Country3:Malaysia)
Note: I'm abusing the function of repr()
to get the quotes in there. You could just as well do "'" + str(k) + "'"
.
The reason why your code doesn't work is your use of :
outside of a dictionary initialization or comprehension. That is, you can do d = {'a':'b'}
but you can't do print 'a':'b'
. Also, you shouldn't use dict
as a variable name, because it is a keyword.
My solution will work for tuples which have more (or even less) than 3 elements in them, too.
Upvotes: 1
Reputation: 123463
There's nothing built-in that I know of that will do it, but it's pretty simple to do what you want:
countries = {
'Europe': ('Germany', 'France', 'Italy'),
'Asia': ('India', 'China', 'Malaysia'),
}
for k, v in countries.iteritems():
print k+':', tuple(map(lambda c: 'Country%d:%s' % c, enumerate(v, start=1)))
Output:
Europe: ('Country1:Germany', 'Country2:France', 'Country3:Italy')
Asia: ('Country1:India', 'Country2:China', 'Country3:Malaysia')
Upvotes: 0
Reputation: 1232
mainDict = {"Europe": ("Germany", "France", "Italy"),
"Asia": ("India", "China", "Malaysia")
}
for item in mainDict:
print "%s:(%s)" % (item, ", ".join(["Country%s:%s" % (r+1, y) for r, y in enumerate(mainDict[item])]))
Print out:
Europe:(['Country1:Germany', 'Country2:France', 'Country3:Italy'])
Asia:(['Country1:India', 'Country2:China', 'Country3:Malaysia'])
Upvotes: 0