Reputation: 251
For example, if
a = {('a','b','c'):2, ('b','c','d'):3}
I want to return only 'a','b'
.
I tried:
for key in a:
return key[0]
but it only returned 'a'
.
Is there a proper way of finding first element without using lambda or counter or stuff like that (this is a basic course in python). So, no other input program.
Upvotes: 1
Views: 1770
Reputation: 14854
do you want something like this
In [4]: a = {('a','b','c'):2, ('b','c','d'):3}
In [5]: [key[0] for key in a.keys()]
Out[5]: ['a', 'b']
The problem with your code is the return
statement... you should hold all the results before returning...
if you want individual elements every time you can use generators
In [19]: def mygenerator():
....: a = {('a','b','c'):2, ('b','c','d'):3}
....: for k in a.keys():
....: yield k[0]
....:
In [20]: mg = mygenerator()
In [21]: print(mg)
<generator object mygenerator at 0x035FA148>
In [22]: for i in mg:
....: print i
....:
a
b
Upvotes: 2
Reputation: 10126
The function (and therefore your for
loop) ends as soon as it hits return
. You should store the values in a list and then return that. Something like:
def getFirstElems(dic):
firstElems = []
for key in dic:
firstElems.append(key[0])
return firstElems
Then if you run that function like this:
a = {('a','b','c'):2, ('b','c','d'):3}
elem1, elem2 = getFirstElems(a)
print "elem1:", elem1
print "elem2:", elem2
You get this output:
elem1: a
elem2: b
Upvotes: 3
Reputation: 7164
from what i can tell you want to loop over the keys of the dict. try
for k in a.keys():
Upvotes: -1