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

Monday, November 7, 2022

[FIXED] How to create a dictionary with only the unique values and associated keys of another dictionary?

 November 07, 2022     dictionary, list, python, set     No comments   

Issue

I have a dictionary (d) with unique keys, however some of the values are not unique. I want to create a dictionary (result) that only contains the unique values. The key associated with the first instance of a unique value in d should be what appears in result.

What is an efficient way to do this?

I've found similar questions with similar data structures that use tuples and sets to eventually arrive at, for example, lists of unique values. I'm unsure how to apply these solutions when I am interested in preserving the original keys and the original data structure.

Any further help would be much appreciated.

d = {
'a': ['1', '1', '0', '0', '0'],
'b': ['0', '1', '0', '0', '0'],
'c': ['0', '1', '0', '0', '0'],
'd': ['1', '1', '0', '0', '0'],
'e': ['0', '1', '0', '0', '0'],
'f': ['0', '1', '0', '0', '1']
}

result = {
'a': ['1', '1', '0', '0', '0'],
'b': ['0', '1', '0', '0', '0'],
'f': ['0', '1', '0', '0', '1']
}

Solution

You can do this,

r = {}
for k,v in d.items():
    if not tuple(v) in r.values():
       r[k] = tuple(v)
{k: list(v) for k, v in r.items()}

output:

{'a': ['1', '1', '0', '0', '0'],
 'b': ['0', '1', '0', '0', '0'],
 'f': ['0', '1', '0', '0', '1']}


Answered By - Rahul K P
Answer Checked By - David Marino (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