In Python, I need a dictionary object which looks like:
{\'a\': 10, \'b\': 20, \'c\': 10, \'d\': 10, \'e\': 20}
I\'ve been able to get th
Your first example can be simplified using a loop:
myDict = {}
for key in ['a', 'c', 'd']:
myDict[key] = 10
for key in ['b', 'e']:
myDict[key] = 20
No specialized syntax or trickery, and I can't think of anything which would be easier to understand.
Regarding your second question, there is no simple and efficient way to do the lookup as in your second example. I can only think of iterating over the keys (tuples) and checking whether the key is in any of them, which isn't what you're looking for. Stick to using a straightforward dict with the keys you want.
In general, if you are aiming for code that can be understood by novices, stick to the basics such as if conditions and for/while loops.
Method:
def multi_key_dict_get(d, k):
for keys, v in d.items():
if k in keys:
return v
return None
Usage:
my_dict = {
('a', 'b', 'c'): 10,
('p', 'q', 'r'): 50
}
value = multi_key_dict_get(my_dict, 'a')
There is one way that comes to mind. Still has the limitation of only having the same contents.
The value of one key can't change another.
key_map = {
'KEY_UP':move_up,
'w':'KEY_UP',
}
for key in key_map
:
# loop over the `dict`
if key_map[key] in key_map:
# one key is the value of the other
target_key = key_map[key]
key_map[key] = key_map[target_key]
# overwrite key white the ontents of the other
I would say what you have is very simple, you could slightly improve it to be:
my_dict = dict.fromkeys(['a', 'b', 'c'], 10)
my_dict.update(dict.fromkeys(['b', 'e'], 20))
If your keys are tuple you could do:
>>> my_dict = {('a', 'c', 'd'): 10, ('b', 'e'): 20}
>>> next(v for k, v in my_dict.items() if 'c' in k) # use .iteritems() python-2.x
10
This is, of course, will return first encountered value, key for which contains given element.
Why not inherit from dict?
class LazyDict(dict):
def keylist(self, keys, value):
for key in keys:
self[key] = value
>>> d = LazyDict()
>>> d.keylist(('a', 'b', 'c'), 10)
>>> d
{'a': 10, 'c': 10, 'b': 10}
but I prefer loop solution
Similar to @SilentGhost but a more declarative syntax (with Python 3.5+) I prefer:
myDict = {
**dict.fromkeys(['a', 'b', 'c'], 10),
**dict.fromkeys(['b', 'e'], 20)
}