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

Thursday, August 4, 2022

[FIXED] How can I print duplicate items from an OrderedDict?

 August 04, 2022     dictionary, exception, ordereddict     No comments   

Issue

My OrderedDict contains 5 key value pairs which result in the word, "Belle". Every letter its own key with values starting from 1 through 5, from left to right, B = 1, e = 2, etc. Printing this OrderedDict returns only 3 letters, B, l and e. Notice, it doesn't print the repeated e and ls. In the code below, I use a for statement to print "Belle" so it can print vertically. My goal is to print the complete word "Belle" vertically, with each letter as a key with its value pair.

text6 = OrderedDict({'B':1, 'e':2, 'l':3, 'l':4, 'e':5})
for key, value in text6.items():
    print(key, value) 

Code above returns:

B 1
e 5
l 4

Desried output:

B 1
e 2 
l 3
l 4
e 5

Solution

Asking a dict (including OrderedDict) to do what you are asking it to do is impossible. A dict of any type can only contain unique keys. All subsequently added pre-existing keys will overwrite the key and reset it's value.

In order to get the output you want to see, we can use a different data structure. In this implementation, we utilize a list which will contain a tuple for each (value, index) pair we will get by iterating through "Belle" using enumerate

list((v, i) for i, v in enumerate("Belle", 1))


Answered By - mj_codec
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • 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