Dictionary keys in Python are unique. Python will resolve D = {'a':1,'a':2} as D = {'a': 2}
You can effectively store multiple values under the same key by storing a list under that key. In your case,
D = {'a': [1, 2]}
This would allow you to access the elements of 'a' by using
D['a'][elementIdx] # D['a'][0] = 1
Answer from schwadan on Stack OverflowDictionary keys in Python are unique. Python will resolve D = {'a':1,'a':2} as D = {'a': 2}
You can effectively store multiple values under the same key by storing a list under that key. In your case,
D = {'a': [1, 2]}
This would allow you to access the elements of 'a' by using
D['a'][elementIdx] # D['a'][0] = 1
You cannot. I set up an identical dictionary, and when attempting to print the key 'a', I received the secondary value, i.e., 2. Keys are meant to be unique.
You could try something like:
x = {}
for i in range(2):
x[f"a{i}"] = i
Which would output key values like a0, a1, etc.
Can a dictionary have two keys of the same value?
python - Dictionary (same value, different key) - Stack Overflow
Dictionary: Same Key, Different Values
How to find the keys with same values in a dictionary?
My approach would be to add one more level,
s={"one":{"data": ["two","three","four"], "test": "successfull"},"two":["five","six"],"three":["ten","nine"]}
Hope that fulfills the requirments
I think the best way to do this is to have lists of lists (dictionaries of lists if you want keys) as the dictionary values, to store multiple entries under the same key, here's the lists of lists:
# setup
class dd_list(dict):
def __missing__(self,k):
r = self[k] = []
return r
d = dd_list()
d['one'].append(["two","three","four"])
d['two'].append(["five","six"])
d['three'].append(["ten","nine"])
#adding 'one' key again
d['one'].append(["test","successful"])
print (d)
#{'three': [['ten', 'nine']], 'two': [['five', 'six']],
#'one': [['two', 'three', 'four'], ['test', 'successful']]}
You'll get the value self for every single entry in self.mapping, of course, since that's the only value you ever store there. Did you rather mean to take a copy/snapshot of self or some of its attributes at that point, then have self change before it gets stored again...?
Edit: as the OP has clarified (in comments) that they do indeed need to take a copy:
import copy
...
self.mapping[self.Id] = copy.copy(self)
or, use copy.deepcopy(self) if self has, among its attributes, dictionaries, lists etc that need to be recursively copied (that would of course include self.mapping, leading to rather peculiar results -- if the normal, shallow copy.copy is not sufficient, it's probably worth adding the special method to self's class to customize deep copying, to avoid the explosion of copies of copies of copies of ... that would normally result;-).
If I understand what you're saying, then this is probably expected behaviour. When you make an assignment in Python, you're just assigning the reference (sort of like a pointer). When you do:
self.mapping[self.Id] = self
then future changes to self will be reflected in the value for that mapping you just did. Python does not "copy" objects (unless you specifically write code to do so), it only assigns references.
Suppose I have a dictionary d = {'x' : 'a', 'x' : 'b'} how can I get the values within the same key?
My dictionary is
G[i].the_Color_Of_Neighbours[vertex] = color_number_of_neighbours
So , the dictionary holds a particular vertex and the color numbers of it's neighbours which is a list. The dictionary looks something like
{ Vertex1 : [1,2,3] , Vertex2: [5,6,1], Vertex3: [6,4,1] ......... }
I would like to store all the vertex's with the same color_number_of_neighbours maybe in another list. So that list could look like
[ [Vertex1, Vertex 4, Vertex 5] , [Vertex7, Vertex6, Vertex0], [Vertex10, Vertex11] ]
This could happen if Vertex1, Vertex4 and Vertex 5 have the same color_number_of_neighbours. And, Vertex7, Vertex6 and Vertex0 have the same color_number_of_neighbours. Vertex10 and Vertex11 have the same color_number_of_neighbours. Also the order of the numbers in the list don't matter, the numbers in the list should just be the same
ie
dict = { a : 10 , a : [30,10]}
What you are trying to do is not possible with dictionaries. In fact, it is contrary to the whole idea behind dictionaries.
Also, your Sets class won't help you, as it effectively gives each name a new (sort of random) hash code, making it difficult to retrieve items from the dictionary, other than checking all the items, which defeats the purpose of the dict. You can not do dict.get(Sets(some_name)), as this will create a new Sets object, having a different hash code than the one already in the dictionary!
What you can do instead is:
Just create a list of
(name, value)pairs, orpairs = zip(names, values) # or list(zip(...)) in Python 3create a dictionary mapping names to lists of values.
dictionary = {} for n, v in zip(names, values): dictionary.setdefault(n, []).append(v)
The first approach, using lists of tuples, will have linear lookup time (you basically have to check all the entries), but the second one, a dict mapping to lists, is as close as you can get to "multi-key-dicts" and should serve your purposes well. To access the values per key, do this:
for key, values in dictionary.iteritems():
for value in values:
print key, value
Instead of wanting multiple keys with the same name, could you getting away of having multiple values per each key?
names = [1]
values = [[1, 2, 3], [4, 5, 6]]
dict = {}
for i in names:
dict[i] = values
for k,v in dict.items():
for v in dict[k]:
print("key: {} :: v: {}".format(k, v))
Output:
key: 1 :: v: [1, 2, 3]
key: 1 :: v: [4, 5, 6]
Then you would access each value like this (or in a loop):
print("Key 1 value 1: {}".format(dict[1][0]))
print("Key 1 value 2: {}".format(dict[1][1]))
Do you mean something like this?
json_data = []
for i in range(1, 11):
json_data.append({'id': i})
Resulting in:
[{'id': 1},
{'id': 2},
{'id': 3},
{'id': 4},
{'id': 5},
{'id': 6},
{'id': 7},
{'id': 8},
{'id': 9},
{'id': 10}]
There are two mis-steps in the current code:
- The
if i not in json_dataline is only looking at the elements of the list, not the value of theidkey inside the dictionary. - The
json_data['id'] = iline is over-writing the list of dictionaries, with a dictionary under the same variable name ofjson_data.
The below code will address both of those mis-steps.
json_data = [ {"id": 1,"name": "Meghan"},
{"id": 2,"name": "Julia"},
{"id": 3,"name": "Kevin"}
]
for i in range(1, 11):
if i not in [d['id'] for d in json_data]:
json_data.append({"id": i})
If you were to print the json_data list after running the code above, it would output the following:
[{'id': 1, 'name': 'Meghan'}, {'id': 2, 'name': 'Julia'}, {'id': 3, 'name': 'Kevin'}, {'id': 4}, {'id': 5}, {'id': 6}, {'id': 7}, {'id': 8}, {'id': 9}, {'id': 10}]
You can use set.difference within a dict comprehension:
In [29]: Result_one_two = {k: set(Dict_one[k]).difference(Dict_two[k]) for k in Dict_one}
In [30]: Result_one_two
Out[30]: {'A': {'a2', 'a3'}, 'B': set(), 'C': {'c4'}}
In [31]: Result_two_one = {k: set(Dict_two[k]).difference(Dict_one[k]) for k in Dict_one}
In [32]: Result_two_one
Out[32]: {'A': set(), 'B': set(), 'C': {'c5'}}
It's better to preserve the values as set at the first place tho. In that case you won't need to call the set for each value. Also note that if you're using Python-3.6+ since dictionaries in these versions are insertion ordered the output will be as expected, otherwise you should use an OrderedDict to keep track of orders. But if the performance is not an issue here and/or you're dealing with a short data set you can just use a list comprehension as is explained in other answers.
Also, as mentioned in comments, if the order of values is important for you in order to take advantage of set operations and yet keep the order you can use a custom ordered set like what's proposed here https://stackoverflow.com/a/10006674/2867928 by Raymond Hettinger.
You can do so:
Result_one_two = {
k: [v for v in vals if v not in Dict_two.get(k, [])]
for k, vals in Dict_one.items()
}
Output:
Result_one_two = {'A': ['a2', 'a3'], 'C': ['c4'], 'B': []}
And second one:
Result_two_one = {
k: [v for v in vals if v not in Dict_one.get(k, [])]
for k, vals in Dict_two.items()
}
Output:
Result_two_one = {'A': [], 'C': ['c5'], 'B': []}