As I was studying Python, I came across this task:
Imagine Python did not have built-in support for sets. Show how we could use dictionaries to represent sets. Write the four set operations | - ^ & for this new representation of sets.
Below you can see the answer:
First, for the ‘or’ operation, we add entries to the new dictionary from both input lists:
l1 = [1,2,3,4,5]
l2 = [4,5,6,7,8]
def t_or(l1,l2):
result = {}
for x in l1: result[x] = 0
for x in l2: result[x] = 0
print(result)
So, I'm wondering why do the author used such a strange method to add entries result[x] = 0
? Isn't there a better way to do it, maybe using alternatives methods like .add
, .insert
, etc?
CodePudding user response:
result[key] = value
is the way to assign a new pair key:value
in a Python dictionary. You don't have to create the entry key first on a Dictionary. If you come from Java, for example, the syntaxis is like:
Map<String, String> result = new HashMap<int, int>();
result.put(1, 0);
As you can see, on Java you are not declaring the key too, the same happens on a lot of languages and that is because of how a dictionary key works.
When you want to retrieve an element from a dictionary, you have to be sure that the key already exists in the dictionary, otherwise it will throw an exception.
The .add
or .insert
that you have in mind in Python is .append
and it is used to add a new element to a list:
my_list = []
my_list.append(0)
So no, there is no a better way or a different way to assign new key:value
pairs on a Python dictionary.
CodePudding user response:
l1 = [1,2,3,4,5]
l2 = [4,5,6,7,8]
result = {}
result["l1"] = l1
result["l2"] = l2
print(result)
This worked for me. result["key"] = yourlist
This is print: {'l1': [1, 2, 3, 4, 5], 'l2': [4, 5, 6, 7, 8]}