Skip to content Skip to sidebar Skip to footer

Print Index Number Of Dictionary?

I'm trying to pull out strictly the index number from the following dictionary: data = {0: {'GAME_ID': '0021600457', 'TEAM_ID': 1610612744}, 1: {'GAME_ID': '0021600457', 'TEAM_ID'

Solution 1:

I think you have mixed up index numbers with keys. Dictionaries are formed like such:

{key: value}

data.keys() will return a list of keys. In your case:

data.keys()
[0,1,2]

From there, you can call the first item, which is 0 (First item in a list is 0, and then progresses by one).

data.keys()[0]0

If you are looking for a specific key by the predefined values, then try:

x = 'GAME_ID'
y = '0021600457'

forindex_num, sub_dict in data.items():
    foreachsub_keysin sub_dict.keys():
        if eachsub_keys == x:
            print(index_num)

forindex_num, sub_dict in data.items():
    foreachsub_valuesin sub_dict.values():
        if eachsub_values == y:
            print(index_num)

Output:
012012

Note: python3 no longer uses .iteritems()

By the way, you are missing a curly brace at the end. It should be like this:

data = {0: {'GAME_ID': '0021600457', 'TEAM_ID': '1610612744'}, 1: {'GAME_ID': '0021600457', 'TEAM_ID': '1610612744'}, 2: {'GAME_ID': '0021600457', 'TEAM_ID': '1610612744'}}

Assuming that you wanted consistency, I've added the missing quotes as well.

Solution 2:

Some more info on dictionary operations in the docs.

This what you want?:

data = {0: {'GAME_ID': '0021600457', 'TEAM_ID': 1610612744},
        1: {'GAME_ID': '0021600457', 'TEAM_ID': 1610612744},
        2: {'GAME_ID': '0021600457', 'TEAM_ID': 1610612744}}

for key in data:
    print (key)

# Outputs:
0
1
2

If you are trying to iterate over the values:

data = {0: {'GAME_ID': '0021600457', 'TEAM_ID': 1610612744},
        1: {'GAME_ID': '0021600457', 'TEAM_ID': 1610612744},
        2: {'GAME_ID': '0021600457', 'TEAM_ID': 1610612744}}

for value indata.values():
    print (value)

# or

for key indata:
    print (data[key])

Solution 3:

Could you clarify where you are getting 'x' from? If you want to print keys, you could just do

for i in dict:
    print(i)

Post a Comment for "Print Index Number Of Dictionary?"