简体   繁体   中英

Naming each item in a list which is a value of a dictionary

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!

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.

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'])

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM