Reputation: 65
I am trying to loop through a dictionary and return the values and corresponding index of the value. So far, I am able to return the entire list.
cdict = {'ZS': [3,3,3,5,5,5,5,7,7,7,7,8,8,11,11,11,11,11,11,1,1,1,1,3]}
for k, v in cdict.items():
print (v)
I would like to be able to return the following: 3, 0 3, 1 3, 2 5, 3 ... 3, 23. Where 0,1,2,3 etc (in the second column) are the respective index positions of the values. Any help is greatly appreciated.
Upvotes: 0
Views: 63
Reputation: 3639
Single-line solution:
a = list(map(lambda v: list(map(lambda x: print("{}, {}".format(*x[::-1])) or x[::-1], enumerate(v))), cdict.values()))
bonus: in a
you could find the following list:
[[(3, 0), (3, 1), (3, 2), (5, 3), (5, 4), (5, 5), (5, 6), (7, 7), (7, 8), (7, 9), (7, 10), (8, 11), (8, 12), (11, 13), (11, 14), (11, 15), (11, 16), (11, 17), (11, 18), (1, 19), (1, 20), (1, 21), (1, 22), (3, 23)]]
Upvotes: 1
Reputation: 21
Not sure if this is what your after but this will print the item in the dict and the index:
cdict = {'ZS': [3,3,3,5,5,5,5,7,7,7,7,8,8,11,11,11,11,11,11,1,1,1,1,3]}
print(cdict['ZS'])
index = -1
for e in cdict['ZS']:
index += 1
print("Index:",index, "item", e)
Upvotes: -1
Reputation: 12332
You've already shown that you can iterate over the dictionary. So what's left is to print the list with indexes. Python has a nice function for that called enumerate
:
for (i, v) in enumerate([3,3,5]):
print(v, i)
3 0
3 1
5 2
Enumerate turns any iteratable into pairs of index and value. So it doesn't just work for list but anything you can iterate.
Upvotes: 1
Reputation: 196
cdict = {'ZS': [3,3,3,5,5,5,5,7,7,7,7,8,8,11,11,11,11,11,11,1,1,1,1,3]}
for k, v in cdict.items():
for idx in range(len(v)):
print('{}, {}'.format(v[idx], idx))
Upvotes: 2