Reputation: 11
I have this dictionary, with some code to print from it:
fichiers_dict= {
'sample1':{'libelle':'sample1.csv','server':'10.21.11.41'},
'sample2':{'libelle':'sample2.csv','server':'192.168.1.40'},
'sample3':{'libelle':'sample3.csv','server':'10.21.7.251'},
'sample4':{'libelle':'sample4.csv','server':'10.21.12.200'}
}
for serveurs in fichiers_dict:
for fichier in fichiers_dict[serveurs]:
print(fichiers_dict[serveurs][fichier]['libelle'])
When I run this, I get the following error:
TypeError: string indices must be integers, not str
What is wrong with the code?
Upvotes: 0
Views: 98
Reputation: 147
If you want to print values with Key - 'libelle'
fichiers_dict= {
'sample1':{'libelle':'sample1.csv','server':'10.21.11.41'},
'sample2':{'libelle':'sample2.csv','server':'192.168.1.40'},
'sample3':{'libelle':'sample3.csv','server':'10.21.7.251'},
'sample4':{'libelle':'sample4.csv','server':'10.21.12.200'}
}
for key, value in fichiers_dict.items():
print(value['libelle'])
Upvotes: 0
Reputation: 8868
for serveurs in fichiers_dict: # keys of fichiers_dict
for fichier in fichiers_dict[serveurs]: # keys of fichiers_dict[serveurs]
print(fichiers_dict[serveurs][fichier]['libelle']) # key(string)['libelle'] -> wrong
As I added in comments, when you iterate directly on dict, its the keys getting iterated.
So fichiers_dict[serveurs][fichier]
is the key libelle
.
If you again to sub-index of the string libelle
, it cannot be a string index, but only integer.
for serveurs in fichiers_dict.values():
print(serveurs['libelle'])
should be enough.
Upvotes: 3