2

How to start the python iteration from second item directly?

d = {
  'name': 'ABC',
  'age': '23',
  'email': 'abc@example.com'  
}

I tried by the following code,

first_item = next(iter(d))
for k, v in d.items():
    print(k, v)

Expected:

age : 23
email : abc@example.com

Actual:

name : ABC
age : 23
email : abc@example.com

Expecting the solution based on 'Python 3' version.

Thanks,

Jai K
  • 375
  • 1
  • 4
  • 12
  • how about a check if the key name of the first element of dict is constant ? you can simply "continue", if k == "name", inside the for loop. Or is it necessary to skip the first element of dict ? – ruhaib Aug 09 '19 at 09:22
  • 2
    Python dicts don't support the element order, so there is no second item. So you yes, skipping the elements by name sounds like a better solution. – bereal Aug 09 '19 at 09:24
  • 1
    @bereal Python dicts from 3.7 on gurantee insert order ... – Patrick Artner Aug 09 '19 at 09:25
  • @PatrickArtner wow, indeed. Do dict literals support that, too? – bereal Aug 09 '19 at 09:28

6 Answers6

3

You're not modifying the dictionary, you're building a new iterator and extracting the first (possibly arbitrary item). You shouldn't be relying on the 'name' being first key anyway for earlier python versions (where dictionaries are not ordered). Instead you can .pop the relevant item:

>>> d = {
...   'name': 'ABC',
...   'age': '23',
...   'email': 'abc@example.com'  
... }
>>> name = d.pop('name')
>>> name
'ABC'
>>> for k, v in d.items():
...     print(k, v)
... 
age 23
email abc@example.com
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
1

Try this:

items = iter(d.items())
first_item = next(items)
for k, v in items:
    print(k, v)

But be careful with Python order dict, better will be skip by key name: Are dictionaries ordered in Python 3.6+?

Kubas
  • 976
  • 1
  • 15
  • 34
0
for i, v in enumerate(d.items()):
    if i == 0:
        pass

    else:
        print({v[0]:v[1]})
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45
0

Just apply list slicing to skip the first element.

But first, you will need to convert d.items() in a list object since it returns a dict_items object.

for k, v in list(d.items())[1:]: print(k, v)
Martin Tovmassian
  • 1,010
  • 1
  • 10
  • 19
0

Just skip the name as d in python is not ordered. If you use OrderedDict from collections, you can use d.items()[1:].

iamsk
  • 346
  • 5
  • 7
0

It's not a optimal solution but it should work for your requirments.

for k,v in d.iteritems():
   if(k=="name"):
       continue
   print(k,v)