简体   繁体   中英

how to return first element in multiple tuples as keys in dictionary

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.

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

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

from what i can tell you want to loop over the keys of the dict. try

for k in a.keys():

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