You can use a list comprehension.
result = list(result)
new_result = [result[i] for i in list_of_indices]
Answer from luthervespers on Stack OverflowI 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.
class MultiKeyDict(object):
def __init__(self, **kwargs):
self._keys = {}
self._data = {}
for k, v in kwargs.iteritems():
self[k] = v
def __getitem__(self, key):
try:
return self._data[key]
except KeyError:
return self._data[self._keys[key]]
def __setitem__(self, key, val):
try:
self._data[self._keys[key]] = val
except KeyError:
if isinstance(key, tuple):
if not key:
raise ValueError(u'Empty tuple cannot be used as a key')
key, other_keys = key[0], key[1:]
else:
other_keys = []
self._data[key] = val
for k in other_keys:
self._keys[k] = key
def add_keys(self, to_key, new_keys):
if to_key not in self._data:
to_key = self._keys[to_key]
for key in new_keys:
self._keys[key] = to_key
@classmethod
def from_dict(cls, dic):
result = cls()
for key, val in dic.items():
result[key] = val
return result
Usage:
>>> d = MultiKeyDict(a=1, b=2)
>>> d['c', 'd'] = 3 # two keys for one value
>>> print d['c'], d['d']
3 3
>>> d['c'] = 4
>>> print d['d']
4
>>> d.add_keys('d', ('e',))
>>> d['e']
4
>>> d2 = MultiKeyDict.from_dict({ ('a', 'b'): 1 })
>>> d2['a'] = 2
>>> d2['b']
2
Is there a particular reason you can't just use a dictionary:
x = {}
x[1] = x['karl'] = dog
x[2] = x['lisa'] = cat
Then you can access it by either.
If you really don't want to repeat your self you do this:
class MysticalDataStructure(dict):
def add(self, key1, key2, value):
return self[key1] = self[key2] = value
x = MysticalDataStructure()
x.add(1, 'karl', dog)
x.add(2, 'lisa', cat)
You can perform the following (comments included):
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for keys, values in d.items(): #Will allow you to reference the key and value pair
for item in values: #Will iterate through the list containing the animals
if item == "DOG":
print(item)
print(values.index(item)) #will tell you the index of "DOG" in the list.
So maybe this will help:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
for animal in (d[item]):
if animal == "DOG":
print(animal)
Update -What if I want to compare the string to see if they're equal or not... let say if the value at the first index is equal to the value at the second index.
You can use this:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
for animal in (d[item]):
if animal == "DOG":
if list(d.keys())[0] == list(d.keys())[1]:
print("Equal")
else: print("Unequal")
you could just do this:
test = {"11.67": 1, "12.67": 2}
res = {key: {"value": str(int(float(key)))} for key in test}
# {'11.67': {'value': '11'}, '12.67': {'value': '12'}}
where i first convert the strings to floats, then discard the fractional part by using int and convert back to str again.
what goes wrong in your code is nicely explained in Carsten's answer.
Your error lies in declaring the temp_dict outside the loop. This works:
test={"11.67":1,"12.67":2}
indexes=test.keys()
final_dict={}
for index in indexes:
temp_dict={}
b=index.split('.')[0]
temp_dict['value']=b;
final_dict.update({index:temp_dict})
print (final_dict)
You can use any immutable and hashable object as key, including tuples
number_of_read_lengths = {}
number_of_read_lengths[14,3] = "Your value"
Using tuples could be quite annoying -- you got to remember to place the tuple during indexing.
I would recommend a nested dict, but a defaultdict, like so:
from collections import defaultdict
number_of_read_lengths = defaultdict(dict)
number_of_read_lengths[1][2] = 3
print(number_of_read_lengths)
This code would give:
defaultdict(<type 'dict'>, {1: {2: 3}})
This way, any non-existing element in the number_of_read_lengths dict will be created as a dict when accessing or setting it. Simple and effective.
More info on defaultdict: http://docs.python.org/library/collections.html#collections.defaultdict
There are also examples: http://docs.python.org/library/collections.html#defaultdict-examples