PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

[FIXED] how append (key,value) with loop on python

 May 12, 2022     append, dictionary, loops, python     No comments   

Issue

I want to create a new dict with a loop but I don't find the way to push key and value in loop with append. I try something like this but I'm still searching the good way.

frigo = {"mangue" : 2, "orange" : 8, "cassoulet" : 1, "thon" : 2, "coca" : 8, "fenouil" : 1, "lait" : 3}
new_frigo  = {} 

for i, (key, value) in enumerate(frigo.items()):
    print(i, key, value)
    new_frigo[i].append{key,value}

Solution

There's already a python function for that:

new_frigo.update(frigo)

No need for a loop! dict.update(other_dict) just goes and adds all content of the other_dict to the dict.

Anyway, if you wanted for some reason to do it with a loop,

for key, value in frigo.items():
  new_frigo[key] = value

would do that. Using an i here makes no sense - a dictionary new_frigo doesn't have indices, but keys.



Answered By - Marcus Müller
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing