'how to get first key for every data dictonary in a loop

lets say i have this

test= {"Default":{"test_data":{"data":"test}},
       "Test":{"abc_data":{"data":"test}},
       "Default":{"zxy_data":{"data":"test}},
      }

with a loop

for t in test:
 first = next(iter(t))
 print(first)

output

D
T
M

how can i get it Default, Test and Master instead of the initial alphabet? edit: i dont need the keys inside but i need Default, Test and Master keys only. Of course this is hard coded but i would like to get it dynamically



Solution 1:[1]

Given:

test = {
    "Default": ["blue", "white"],
    "Test": ["pink", "brown"],
    "Master": ["pink", "brown"]
}

If you want to access both keys and values:

for key, value in test.items():
    print(key)
    print(value)

or keys only:

for key in test.keys():
    print(key)

What do you mean with first key? Check OrderedDict, a variant that remembers the order the keys were last inserted.

Solution 2:[2]

test = {"Default":["blue","white"],
       "Test":["pink","brown"],
       "Master":["pink","brown"]
      }

for k, v in test.items():
    print(k)
    print(v)

print(test.keys())

output

Default
['blue', 'white']
Test
['pink', 'brown']
Master
['pink', 'brown']
dict_keys(['Default', 'Test', 'Master'])

Solution 3:[3]

In Python you can iterate over the keys, values and (key, value) pair of a dictionary as follows...

for key in test.keys():
  print('key : ', key)

print()

for value in test.values():
    print('value : ', value)

print()

for item in test.items():
    print('item : ', item)

Output...

key :  Default
key :  Test
key :  Master

value :  {'test_data': {'data': 'test'}}
value :  {'abc_data': {'data': 'test'}}
value :  {'zxy_data': {'data': 'test'}}

item :  ('Default', {'test_data': {'data': 'test'}})
item :  ('Test', {'abc_data': {'data': 'test'}})
item :  ('Master', {'zxy_data': {'data': 'test'}})

Now let's come to your code and see what is happening...

The code below will print the keys. i.e. the variable "item" will contain the key in string format.

for item in test:
    print(item)

Output...

Default
Test
Master

You have made the key string using the function iter() function and tried to iterrate over the characters of the key string using next() function. But the correct way to iterate over a string is given below...

s = iter('abcd')
while True:
    try:
        item = next(s)
        print(item)
    except StopIteration as exception:
        break

Output...

a
b
c
d

Since you have not used the next() funtion inside any loop, it printed only the first character of the key. In the next iteration next key was selected and thus it printed the furst letter of the second key and so on.

Now let's modify your code so that you can get your expected result...

for item in test:
    key        = iter(item)
    key_string = ''
    while True:
        try:
            character   = next(key)
            key_string += character
        except StopIteration as exception:
            break
    print('Key : ', key_string)

Output...

Key :  Default
Key :  Test
Key :  Master

You can try to make you own iterator to understand the StopIteration exception.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Giancarlo Romeo
Solution 2 CN-LanBao
Solution 3