anon
anon

Reputation: 866

Given a dictionary how can I check if two of its keys are the same?

I have one dictionary:

dict_one={'a':'the quick brown fox.','b':'the quick brown fox.', 'c':'good night guys',...,'n':'hey there'}

how can I check if key a and key b string values are the same and add a new key to the dictionary equals to the dictionary showing me if they are different or equal values (True/False)?

dict_one={'a':'the quick brown fox.','b':'the quick brown fox.', 'c':'good night guys',...,'n':'hey there', 'equals':True}

I tried to:

for i,j in dict_one.iteritems():
 if (a==b):
     return 'True'
 else:
      return 'False'

Upvotes: 0

Views: 56

Answers (3)

wjandrea
wjandrea

Reputation: 32987

You ask two different questions:

Given a dictionary how can I check if two of its keys are the same?

A dict by definition can't have duplicate keys.

How can I check if key a and key b string values are the same and add a new key to the dictionary equals if they are different or equal values (True/False)?

This compares the values of keys a and b and assigns the result to key equals:

dict_one['equals'] = dict_one['a'] == dict_one['b']

Upvotes: 2

JohnO
JohnO

Reputation: 777

So from your example you only want to check whether any two values (not keys as you write in your question title) are the same, but you don't care which ones those are. The fastest and easiest way of doing that is probably

len(set(dict_one.values())) < len(dict_one)

This converts all values of the dict into a set which, if there are any duplicates, will contain fewer items than the original dict. So the above code will return true if any values in the dict are duplicated and it will run in O(n) rather than O(n^2) which the solution you attempted would have taken.

Edit: for completeness:

dict_one['equals'] = len(set(dict_one.values())) < len(dict_one)

will set the entry in the dict as you requested

Upvotes: 2

sahasrara62
sahasrara62

Reputation: 11228

use dict.update()

dict_one={'a':'the quick brown fox.','b':'the quick brown fox.', 'c':'good night guys','n':'hey there'}

dic = {'equal':True} if dict_one['a']==dict_one['b'] else {'equal':False}

dict_one.update(dic)
print(dict_one)

output

dict_one={'a':'the quick brown fox.','b':'the quick brown fox.', 'c':'good night guys',...,'n':'hey there'}

Upvotes: -1

Related Questions