This question already has answers here:
switching keys and values in a dictionary in python [duplicate]
(10 answers)
Closed 6 years ago.
I am currently preparing for a python exam and one topic we are expected to understand is having to flip a dictionary in which values become the keys and the keys become values. I am confused as to what this asking and if someone could provide me with a basic example to see what it looks like I would greatly appreciate it.
Simply write a dict comprehension expression and make it's key as value and values as key. For example:
>>> my_dict = {1: 2, 3: 4, 5: 6}
>>> {value: key for key, value in my_dict.items()}
{2: 1, 4: 3, 6: 5}
Note: Since, dict contains unique keys. In case you have same element as value for multiple keys in your original dict, you will loose related entries. For example:
# Same values v v
>>> my_dict = {1: 2, 3: 4, 5: 2}
>>> {value: key for key, value in my_dict.items()}
{2: 5, 4: 3}
#^ Only one entry of `2` as key
Related
This question already has answers here:
Is it possible to assign the same value to multiple keys in a dict object at once?
(8 answers)
Closed 3 years ago.
Is there a compact way to have alternative keys for the same value in a dictionary?
Taking a dictionary like the following
dict={'A':1,'B':2,'one':1,'two':2}
I can obtain the value 1 using two different keys:
dict['A']
dict['one']
I would like to know if there is a more compact way to write it, something akin to:
dict2={['A','one']:1,['B','two']:2}
You can define the dict with keys of the same value grouped as a tuple first:
d = {('A', 'one'): 1, ('B', 'two'): 2}
so that you can then convert it to the desired dict with:
d = {key: value for keys, value in d.items() for key in keys}
d becomes:
{'A': 1, 'one': 1, 'B': 2, 'two': 2}
This question already has answers here:
Access an arbitrary element in a dictionary in Python
(14 answers)
Closed 3 years ago.
I have a dictionary and don't know the keys or values. I want to remove a single element (doesn't matter which) and create a new dictionary containing only that key and value, removing it from the old dictionary in the process.
dict(n items) -> newdict(1 item) and dict(n-1 items)
What I've tried:
newdict=dict.pop() - Would work perfectly for a list, but for dictionary it 1. requires a key and only returns a value, not a new dictionary or a key, value pair
newdict={dict.items()[0]} - TypeError: 'dict_items' object is not subscriptable
newdict={dict.keys()[0],dict.pop(dict.keys()[0])} - TypeError: 'dict_keys' object is not subscriptable
key=list(dict)[0] newdict={key,dict.pop(key)} - Works (finally), but isn't their a better way than converting the entire dictionary to a list just to grab one key?
Is there a more efficient way to move a single dictionary element into a new dictionary?
Edit: Having the single element as a tuple would also work. I just need both the key and value of the element I remove.
I think this is a good use-case for dict.popitem:
old_dict = {1: 2, 3: 4, 5: 6}
new_dict = {7: 8}
def move_item(old, new):
k, v = old.popitem()
new[k] = v
move_item(old_dict, new_dict)
print(old_dict, new_dict)
with result
{1: 2, 3: 4} {7: 8, 5: 6}
You can iterate
for key, value in dict.items():
if value == bla:
dict.pop(key)
Try:
for key, value in old_dict:
new_dict[key] = old_dict.pop(key)
# operate with new_dict
This question already has answers here:
How do I merge a list of dicts into a single dict?
(11 answers)
Closed 5 years ago.
Right now i have this:
A={0:[{1:2},{2:3}],
1:[{4:5},{5:6}]}
And I want to change this dictionary to the following:
A={0:{1:2,2:3},
1:{4:5,5:6}}
Is this possible?
Try doing this: Iterate over the elements int the list and merge them into temp_dict. assign temp_dict to the key of the original dictionary.
A={0:[{1:2},{2:3}],
1:[{4:5},{5:6}]}
for k,v in A.items():
temp_dict={}
for elem in v:
for k2,v2 in elem.items():
temp_dict[k2] = v2
A[k] = temp_dict
print A
# prints {0: {1: 2, 2: 3}, 1: {4: 5, 5: 6}}
This question already has answers here:
How do I exchange keys with values in a dictionary? [duplicate]
(19 answers)
Closed 7 years ago.
I want to interchange keys and value in a given dictionary. For example:
dict = {1:'sandeep', 2: 'suresh', 3: 'pankaj'}
will become:
dict1 = {'sandeep': 1, 'suresh': 2, 'pankaj': 3}
Using zip is probably better than a dictionary comprehension:
dict1 = dict(zip(dict1.values(), dict1.keys())) # better for beginners
In [45]: d = {1:'sandeep',2 : 'suresh', 3: 'pankaj'}
In [46]: {(v, k) for k,v in d.iteritems()}
Out[46]: {'pankaj': 3, 'sandeep': 1, 'suresh': 2}
Note the use of d as the variable name instead of the built-in dict.
Also note that you are not guaranteed uniqueness and can loose entries:
In [47]: d = {1:'sandeep',2 : 'suresh', 3: 'pankaj', 4:'suresh'}
In [48]: {(v, k) for k,v in d.iteritems()}
Out[48]: {'pankaj': 3, 'sandeep': 1, 'suresh': 4}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
syntax to insert one list into another list in python
How could be the syntax for creating a dictionary into another dictionary in python
You can declare a dictionary inside a dictionary by nesting the {} containers:
d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}
And then you can access the elements using the [] syntax:
print d['dict1'] # {'foo': 1, 'bar': 2}
print d['dict1']['foo'] # 1
print d['dict2']['quux'] # 4
Given the above, if you want to add another dictionary to the dictionary, it can be done like so:
d['dict3'] = {'spam': 5, 'ham': 6}
or if you prefer to add items to the internal dictionary one by one:
d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8
dict1 = {}
dict1['dict2'] = {}
print dict1
>>> {'dict2': {},}
this is commonly known as nesting iterators into other iterators I think
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']