我是python的新手,我想知道是否有办法在特定索引处提取值。假设我有一个键,其中包含多个与之关联的值(list
(。
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
假设我想遍历值并打印出值(如果它等于"DOG"(。值,键对是否有与值的位置关联的特定索引?
我尝试阅读字典及其工作原理,显然您无法真正索引它。我只是想知道是否有办法解决这个问题。
您可以执行以下操作(包括注释(:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for keys, values in d.items(): #Will allow you to reference the key and value pair
for item in values: #Will iterate through the list containing the animals
if item == "DOG":
print(item)
print(values.index(item)) #will tell you the index of "DOG" in the list.
所以也许这会有所帮助:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
for animal in (d[item]):
if animal == "DOG":
print(animal)
更新 - 如果我想比较字符串以查看它们是否相等怎么办......假设第一个索引的值是否等于第二个索引的值。
您可以使用它:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
for animal in (d[item]):
if animal == "DOG":
if list(d.keys())[0] == list(d.keys())[1]:
print("Equal")
else: print("Unequal")
字典中的键和值按键索引,不像列表中那样具有固定索引。
但是,您可以利用"OrderedDict"的使用为您的词典提供索引方案。它很少使用,但很方便。
话虽如此,python3.6 中的字典是按插入顺序排列的:
更多关于这里:
字典是在 Python 3.6+ 中排序的吗?
d = {'animal': ['cat', 'dog', 'kangaroo', 'monkey'], 'flower': ['hibiscus', 'sunflower', 'rose']}
for key, value in d.items():
for element in value:
if element is 'dog':
print(value)
这有帮助吗? 或者,您想打印字典中键的索引吗?