I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
- Python's strings and numbers are immutable objects,
- So, if you want
d['a']andd['b']to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or adict,list,set). - Then, when you modify the object at
d['a'],d['b']changes at same time because they both point to same object.
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
- Python's strings and numbers are immutable objects,
- So, if you want
d['a']andd['b']to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or adict,list,set). - Then, when you modify the object at
d['a'],d['b']changes at same time because they both point to same object.
If you're going to be adding to this dictionary frequently you'd want to take a class based approach, something similar to @Latty's answer in this SO question 2d-dictionary-with-many-keys-that-will-return-the-same-value.
However, if you have a static dictionary, and you need only access values by multiple keys then you could just go the very simple route of using two dictionaries. One to store the alias key association and one to store your actual data:
alias = {
'a': 'id1',
'b': 'id1',
'c': 'id2',
'd': 'id2'
}
dictionary = {
'id1': 1,
'id2': 2
}
dictionary[alias['a']]
If you need to add to the dictionary you could write a function like this for using both dictionaries:
def add(key, id, value=None)
if id in dictionary:
if key in alias:
# Do nothing
pass
else:
alias[key] = id
else:
dictionary[id] = value
alias[key] = id
add('e', 'id2')
add('f', 'id3', 3)
While this works, I think ultimately if you want to do something like this writing your own data structure is probably the way to go, though it could use a similar structure.
multiple values for one key in a dictionary
A dictionary key can only hold one value. But that one value could be a list:
dic = {
"some_value": [1, 2, 3],
} More on reddit.com Dictionaries of one key with multiple values.
python - A dictionary that allows multiple keys for one value - Code Review Stack Exchange
Python: How to assign multiple values to a key in dictionary without concatenating the value?
This has been solved now
is there any way for me to create a dictionary with a key having two values?
ex.
dic = {
1:2:3
}
this gives me a syntax error which isn't due to indentation so is it just not possible
I'm trying to create a shop kinda thing and was wondering if it was possible?
A dictionary key can only hold one value. But that one value could be a list:
dic = {
"some_value": [1, 2, 3],
}
You can use tuples as a key:
dic = {(1,2,3): "x"}
It isn't possible to use lists as a key though (since lists are unhashable), but in principle, yes, it's possible.
fwiw I have never done this and I'm rather skeptical about why you might want to do it, but it is possible.
Hi. What I am trying to do is assign multiple values to one dictionary key. and the way I have figured out this is with a list as a key but I am having a little problem. Below is the code I am trying to run.
stock = {'1001' : ['5','3.5'], '1002' : ['8', '1.50']}
purchase = int(input("Please enter the code of the item: "))
if purchase in stock:
stock[[purchase][0]] =- 1
print(stock)I have already created a dictionary with keys and values as lists. I am then asking for input about an item code. I then want to check the entered code against the dictionary keys and if the key is valid I want to subtract one from the quantity which is the first element in each value list. ex - there are 5 items with the key '1001', I enter the code '1001', the program should know print out the dictionary saying there are 4 items now remaining woth the code '1001'. The problem I am facing is the deduction is not happening. After I enter the item code the dictionary is printed as it is the desired subtraction is not occurring.
Thank you to anyone who helps.
I'm still a beginner (but having fun!!) Here is my code with the output:
p_book = {}
while True:
phone_book = int(input("command (1 search, 2 add, 3 quit):"))
if phone_book == 3:
print("quitting...")
break
elif phone_book == 1:
name = input("name: ")
if name in p_book:
print(p_book[name])
else:
print("no number")
elif phone_book == 2:
name = input("name: ")
num = input("number: ")
if name in p_book:
if num not in p_book:
p_book[name] += num
print("ok!")
else:
continue
elif name not in p_book:
p_book[name] = num
print("ok!")
________________________________________________________________________________________________________
my input was name: Mary and 2 different "Phone numbers": 045-1212344 and 045-9999999
here is the output:
command (1 search, 2 add, 3 quit):2
name: Mary
number: 045-1212344
ok!
command (1 search, 2 add, 3 quit):2
name: Mary
number: 045-9999999
ok!
command (1 search, 2 add, 3 quit):1
name: Mary
045-1212344045-9999999
_____________________________________________________________________________________________________
what I need to output is the two numbers as separate numbers. I know if I have the two numbers (values) in the dictionary listed separately I can use a for list to print out the numbers on a separate line like so:
name: Mary
045-1212344
045-9999999
_______________________________________________________________________________________________________
Happy Father's Day!!!
What type are the values?
dict = {'k1':MyClass(1), 'k2':MyClass(1)}
will give duplicate value objects, but
v1 = MyClass(1)
dict = {'k1':v1, 'k2':v1}
results in both keys referring to the same actual object.
In the original question, your values are strings: even though you're declaring the same string twice, I think they'll be interned to the same object in that case
NB. if you're not sure whether you've ended up with duplicates, you can find out like so:
if dict['k1'] is dict['k2']:
print("good: k1 and k2 refer to the same instance")
else:
print("bad: k1 and k2 refer to different instances")
(is check thanks to J.F.Sebastian, replacing id())
Check out this - it's an implementation of exactly what you're asking: multi_key_dict(ionary)
https://pypi.python.org/pypi/multi_key_dict (sources at https://github.com/formiaczek/python_data_structures/tree/master/multi_key_dict)
(on Unix platforms it possibly comes as a package and you can try to install it with something like:
sudo apt-get install python-multi-key-dict
for Debian, or an equivalent for your distribution)
You can use different types for keys but also keys of the same type. Also you can iterate over items using key types of your choice, e.g.:
m = multi_key_dict()
m['aa', 12] = 12
m['bb', 1] = 'cc and 1'
m['cc', 13] = 'something else'
print m['aa'] # will print '12'
print m[12] # will also print '12'
# but also:
for key, value in m.iteritems(int):
print key, ':', value
# will print:1
# 1 : cc and 1
# 12 : 12
# 13 : something else
# and iterating by string keys:
for key, value in m.iteritems(str):
print key, ':', value
# will print:
# aa : 12
# cc : something else
# bb : cc and 1
m[12] = 20 # now update the value
print m[12] # will print '20' (updated value)
print m['aa'] # will also print '20' (it maps to the same element)
There is no limit to number of keys, so code like:
m['a', 3, 5, 'bb', 33] = 'something'
is valid, and either of keys can be used to refer to so-created value (either to read / write or delete it).
Edit: From version 2.0 it should also work with python3.