简体   繁体   中英

Enumerate list and print the index and selected values of dictionary

I have the following example code:

contact_book = []

contact = {'Name:': 'Foo', 'Surname:': 'Bars', 'Adress:': 'Foostreet, 3',
           'Number:': '123456'}
contact2 = {'Name:': 'Boo', 'Surname:': 'Bark', 'Adress:': 'Boostreet, 31',
           'Number:': '6554321'}
contact3 = {'Name:': 'Coo', 'Surname:': 'Barf', 'Adress:': 'Coostreet, 32',
            'Number:': '999999'}

contact_book.append(contact)
contact_book.append(contact2)
contact_book.append(contact3)

print(list(enumerate(contact_book)))

the output is:

[(0, {'Name:': 'Foo', 'Surname:': 'Bars', 'Adress:': 'Foostreet, 3', 'Number:': '123456'}), (1, {'Name:': 'Boo', 'Surname:': 'Bark', 'Adress:': 'Boostreet, 31', 'Number:': '6554321'}), (2, {'Name:': 'Coo', 'Surname:': 'Barf', 'Adress:': 'Coostreet, 32', 'Number:': '999999'})]

I want to output only with the index position of the contact and then the values of the keys 'Name' and 'Surname' .

[(0, {'Name:': 'Foo', 'Surname:': 'Bars',}), (1, {'Name:': 'Boo', 'Surname:': 'Bark'}), (2, {'Name:': 'Coo', 'Surname:': 'Barf'})]

How can I access only the Name and the Surname value, additionally with the index position of the contact? I tried it with list enumerate, but I'm open too for other approaches.

You can build dicts containing only the required keys in a list comprehension, generating the corresponding indices in the comprehension using enumerate like so:

keys = ('Name', 'Surname')
lst = [(i, {k: d[k] for k in keys}) for i, d in enumerate(contact_book)]

One can loop through each contact and get values as follows:

outlist = [] 
counter =0
for onedict in contact_book:
    oneitem = []
    oneitem.append(counter)
    oneitem.append( {"Name:":contact["Name:"], "Surname:":contact["Surname:"]} ) 
    outlist.append(oneitem)
    counter += 1

print(outlist)

Output:

[[0, {'Surname:': 'Bars', 'Name:': 'Foo'}], [1, {'Surname:': 'Bars', 'Name:': 'Foo'}], [2, {'Surname:': 'Bars', 'Name:': 'Foo'}]]

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