Python - Comment boucler un dictionnaire
Dans ce tutoriel, nous allons vous montrer comment boucler un dictionnaire en Python.
1. pour la clé dans dict:
1.1 To loop all the keys from a dictionary – for k in dict:
for k in dict:
print(k)
1.2 To loop every key and value from a dictionary – for k, v in dict.items():
for k, v in dict.items():
print(k,v)
P.S items() works in both Python 2 and 3.
2. Exemple Python
Exemple complet.
test_dict.py
def main():
stocks = {
'IBM': 146.48,
'MSFT':44.11,
'CSCO':25.54
}
#print out all the keys
for c in stocks:
print(c)
#print key n values
for k, v in stocks.items():
print("Code : {0}, Value : {1}".format(k, v))
if __name__ == '__main__':
main()
Sortie
MSFT IBM CSCO Code : MSFT, Value : 44.11 Code : IBM, Value : 146.48 Code : CSCO, Value : 25.54
P.S Tested with Python 2.7.10 and 3.4.3