Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - 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': 1610612744}, 2: {'GAME_ID': '0021600457', 'TEAM_ID': 
1610612744}

I'd like to be able to do something like

print(data[x])

And have it return:

0

I'm sure this is something simple that I'm overlooking?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

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

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

Output:
0
1
2

0
1
2

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...