create account

Python Tips 3 - Convert two lists into a dictionary by slashformotion

View this thread on: hive.blogpeakd.comecency.com
· @slashformotion ·
$0.75
Python Tips 3 - Convert two lists into a dictionary
# Python Tips - Convert two lists into a dictionary


![by me](https://files.peakd.com/file/peakd-hive/slashformotion/hOc41Xc3-image.png)

Aujourd'hui nous allons voir quelque chose d'assez simple mais qui peut s'avérer très utile. Quand on programme en Python, on aime bien trouver des moyens de raccourcir le code quand c'est possible. A cet effet, Python intègre de très nombreuses fonction et méthodes de classes très utiles. 

---

> Mais alors qu'allons nous apprendre ?

Nous allons apprendre à construire ce dictionnaire :
```Json
{
    'apples': 5,
    'beans': 8, 
    'cherry': 7
}
```

À partir des listes suivantes:
```Python
quantity = [5, 8, 7]
item_name = ["apples", "beans", "cherry"]
```

> AH, facile ça ! il suffit de faire une petite boucle `for ... in ...:`

Et vous n'auriez pas faux.. Ça donne ceci
```Python
# METHOD 1 
result = {}
for i in range(0, min(len(quantity), len(quantity))):
    key = item_name[i]
    value = quantity[i]
    result[key] = value
```
Le résultat:
```Python
>>>print(result)
{'apples': 5, 'beans': 8, 'cherry': 7}
```

> Génial, ça marche ! Mais c'est un peu long. 

À ça oui c'est un peu long, c'est même plutôt long...

---

Voici une méthode plus rapide: 
```Python
result2 = dict(zip(item_name, quantity))
```
Le résultat:
```Python
>>>print(result2)
{'apples': 5, 'beans': 8, 'cherry': 7}
```

HA ! une ligne ! trop facile!

> Trop bien gros malin, comment ça marche cette ligne magique

### *Décortiquons ça ensemble.*

La fonction `zip()` prend en paramètre un nombre n d'itérateurs (des listes ici) et renvoie une série de tuples accolant les valeurs des listes.

Un exemple vaut milles mots, regardez:
```Python
>>>print(list(zip(chiffres, mots)))

[('apples', 5), ('beans', 8), ('cherry', 7)]
```
Quand au `dict()` c'est le constructeur de la classe dictionnaire. Quand il prend une liste de tuple en arguments, il prend construit le dictionaire en mettant la première valeur du tuple en clé et la seconde en value. 




![author: @thepeakstudio](https://images.hive.blog/0x0/https://images.hive.blog/DQmSkA2zZKCkkqxJKiG1srWbDzi4V74KMnRmg7LfbQDka6z/dividers-06.png)
Vous pourrez retrouver une bonne partie des articles de ce compte [sur ce repo](https://github.com/slashformotion/hive-base).

Pour accéder directement la section que vous regardez actuellement [cliquer ici](https://github.com/slashformotion/hive-base/tree/master/content/series/PythonTips/PythonTips_n3-ConvertTwoListsIntoADictionary).

---
Vous êtes arrivé à la fin, bravo! Si vous avez des questions, n'oubliez pas de les poser. A la prochaine ! 
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorslashformotion
permlinkpython-tips-3-convert-two-lists-into-a-dictionary
categoryhive-163521
json_metadata{"app":"peakd/2020.07.1","format":"markdown","tags":["python","dict","laruche","fr","stem"],"users":["thepeakstudio"],"links":["/@thepeakstudio","https://github.com/slashformotion/hive-base","https://github.com/slashformotion/hive-base/tree/master/content/series/PythonTips/PythonTips_n3-ConvertTwoListsIntoADictionary"],"image":["https://files.peakd.com/file/peakd-hive/slashformotion/hOc41Xc3-image.png","https://images.hive.blog/DQmSkA2zZKCkkqxJKiG1srWbDzi4V74KMnRmg7LfbQDka6z/dividers-06.png"]}
created2020-07-03 10:45:21
last_update2020-07-03 10:45:21
depth0
children5
last_payout2020-07-10 10:45:21
cashout_time1969-12-31 23:59:59
total_payout_value0.375 HBD
curator_payout_value0.370 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length2,576
author_reputation2,410,764,686,560
root_title"Python Tips 3 - Convert two lists into a dictionary"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id98,315,782
net_rshares2,758,270,974,943
author_curate_reward""
vote details (55)
@gitplait-mod2 ·
@slashformotion, great tutorial but it could have been best if you had an English translation along side this post. It had to make use of Google translate to read your blog.

Anyway, thanks for sharing 👍

<sub> **Your post has been submitted to be manually curated by @gitplait community account because this is the kind of publications we like to see in our community.** </sub>

Join our [Community on Hive](https://hive.blog/trending/hive-103590) and Chat with us on [Discord](https://discord.gg/CWCj3rw).

[[Gitplait-Team]](https://gitplait.tech/)
properties (22)
authorgitplait-mod2
permlinkre-slashformotion-qcwhgn
categoryhive-163521
json_metadata{"tags":["hive-163521"],"app":"peakd/2020.07.1"}
created2020-07-03 15:53:12
last_update2020-07-03 15:53:12
depth1
children4
last_payout2020-07-10 15:53:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length550
author_reputation28,898,670,427
root_title"Python Tips 3 - Convert two lists into a dictionary"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,320,582
net_rshares0
@slashformotion ·
Thank you for the advice! I will consider that, but I'm not very good in English so ...
properties (22)
authorslashformotion
permlinkre-gitplait-mod2-qcwt4k
categoryhive-163521
json_metadata{"tags":["hive-163521"],"app":"peakd/2020.07.1"}
created2020-07-03 20:05:09
last_update2020-07-03 20:05:09
depth2
children3
last_payout2020-07-10 20:05:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length87
author_reputation2,410,764,686,560
root_title"Python Tips 3 - Convert two lists into a dictionary"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,324,383
net_rshares0
@gitplait-mod2 ·
Oh yeah, I totally understand. You can also make use of a translator.
properties (22)
authorgitplait-mod2
permlinkre-slashformotion-qcwtq8
categoryhive-163521
json_metadata{"tags":["hive-163521"],"app":"peakd/2020.07.1"}
created2020-07-03 20:19:06
last_update2020-07-03 20:19:06
depth3
children2
last_payout2020-07-10 20:19:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length69
author_reputation28,898,670,427
root_title"Python Tips 3 - Convert two lists into a dictionary"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,324,627
net_rshares0