Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a dict value using another key of the same dict [duplicate]

I want to do something like this:

my_dict = {"key": "value", "key1": "value1", "key2": my_dict["key"]}

and have the result be:

{"key": "value", "key1": "value1", "key2": "value"}

Currently getting unresolved reference unless I declare the dict() prior. Otherwise I get a key error.

like image 957
Nicolas Avatar asked Feb 17 '17 01:02

Nicolas


People also ask

Can dictionary have duplicate keys with different values?

You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary.

Can dictionary contain duplicate keys?

[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .

Can we repeat key in dictionary python?

Python dictionary doesn't allow key to be repeated.

Can a dictionary have two key value pairs with the same key Python?

Dictionary in python are ordered, changeable, and do not allow duplicates. That means the dictionary cannot have two items with the same key; hence, dictionary keys are immutable.


Video Answer


1 Answers

Set the value of key2 to something phony (say, None), initialize my_dict properly, and then change the value of my_dict['key2'] to my_dict["key"].

like image 84
DYZ Avatar answered Oct 07 '22 11:10

DYZ