简体   繁体   中英

Problem with retrieving the value of item in list/dictionary of objects in Python3

I'm trying to put string variables into list/dictionary in python3.7 and trying to retrieve them later for use.

I know that I can create a dictionary like:

string_dict1 = {"A":"A", "B":"B", "C":"C", "D":"D", "E":"E", "F":"F"}

and then retrieve the values, but it is not I want in this specific case.

Here is the code:

A = ""
B = "ABD"
C = ""
D = "sddd"
E = ""
F = "dsas"


string_dict = {A:"A", B:"B", C:"C", D:"D", E:"E", F:"F"}
string_list = [A,B,C,D,E,F]
for key,val in string_dict.items():
    if key == "":
        print(val)


for item in string_list:
    if item == "":
        print(string_list.index(item))

The result I got is:

E
0
0
0

And the result I want is:

A
C
E
0
2
4

If you print string_dict you notice the problem:

string_dict = {A:"A", B:"B", C:"C", D:"D", E:"E", F:"F"}
print(string_dict)
# output: {'': 'E', 'ABD': 'B', 'sddd': 'D', 'dsas': 'F'}

It contains a single entry with the value "" .
This is because you are associating multiple values ​​to the same key, and this is not possible in python, so only the last assignment is valid (in this case E:"E" ).

If you want to associate multiple values ​​with the same key, you could associate a list:

string_dict = {A:["A","C","E"], B:"B", D:"D", F:"F"}

Regarding the list of strings string_list , you get 0 since the method .index(item) returns the index of the first occurrence of item in the list. In your case 0. For example, if you change the list [A,B,C,D,E,F] to [B,B,C,D,E,F] . Your code will print 2 .

If you want to print the index of the empty string in your list:

for index, value in enumerate(string_list):
    if value == '':
        print(index)

Or in a more elegant way you can use a list comprehension:

[i for i,x in enumerate(string_list) if x=='']

Well, I don't think there's a way to get what you want from a dictionary because of how they work. You can print your dictionary and see that it looks like this:

{'': 'E', 'ABD': 'B', 'sddd': 'D', 'dsas': 'F'}

What happened here is A was overwritten by C and then E.

But I played around with the list and here's how I got the last three digits right:

for item in string_list:
    if item != '':
        print(string_list.index(item) - 1)

This prints:

0
2
4

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