I have the following data set:
data=[(('a','b','c'),('x','y','z'))]
How can I convert this into dictionary such that there is mapping as shown below:
d={'a':'x','b':'y','c':'z'}
Since we're playing code golf :)
dict(zip(*data[0]))
You can simply zip the two tuple and operate using dict.
In [189]: dict(zip(data[0][0], data[0][1]))
Out[189]: {'a': 'x', 'b': 'y', 'c': 'z'}
data=[(('a','b','c'),('x','y','z'))]
dictVal = {}
for key, val in zip(data[0][0], data[0][1]):
dictVal[key] = val
You can do so with a dictionary comprehension.
d = {key:value for key in data[0][0] for value in data[0][1]}
You can use dictionary comprehensions like this with multiple variables and for loops to make a dictionary from two different iterables.
Related
I want to add two zeros on a dictionary as values. When i do this the python dictionary returns only a single zero. I don't want to use a list. Why the dictionary behaves like this?
dictionary = {}
#new key and values
dictionary['a'] = {0.0,0.0}
#expected result {'a': {0.0,0.0}}
print(dictionary)
the console returns this as an output.
{'a': {0.0}}
If you don't want to use lists, you can use a tuple, which unlike sets allows duplicates.
In [1]: dictionary = {}
In [2]:
...: dictionary['a'] = (0.0,0.0)
In [3]:
...: print(dictionary)
{'a': (0.0, 0.0)}
d={'a':'Apple','b':'ball','c':'cat'}
The above dictionary I have and I want my Output like the below-mentioned result
res="a=Apple,b=ball,c=cat"
Is it possible in a pythonic way then please answer it I have tried various method but did not get desired output?
Read your dictionary as key/value pairs (dict.items()) and then just format them in a string you like:
d = {'a': 'Apple', 'b': 'ball', 'c': 'cat'}
res = ",".join("{}={}".format(*i) for i in d.items()) # a=Apple,c=cat,b=ball
The order, tho, cannot be guaranteed for a dict, use collections.OrderedDict() if order is important.
One way is to iterate via dict.items and use multiple str.join calls.
d = {'a':'Apple','b':'ball','c':'cat'}
res = ','.join(['='.join(i) for i in d.items()])
# 'a=Apple,b=ball,c=cat'
If you need items ordered by key, use sorted(d.items()).
def format_dict(d):
vals = list(d.values())
return "={},".join(d.keys()).format(*vals) + "={}".format(vals[-1])
d = {'a': 'Apple', 'b': 'ball', 'c': 'cat'}
format_dict(d) # -> 'a=Apple,b=ball,c=cat'
This joins all the keys into a large string containing replacement fields that we then format passing the dict values as args. There wasn't a trailing replacement field so we concatenate the last value in the dictionary to our large string.
For anyone coming here looking for a way to explicitly extract the dictionary keys and values (e.g. if further formatting is required):
d = {'a':'Apple','b':'ball','c':'cat'}
res = ','.join(f'{k}={v}' for k, v in d.items())
# --> a=Apple, b=ball, c=cat
(uses python 3.6+ f-strings)
Say I have a dictionary with many items that have the same values; for example:
dict = {'hello':'a', 'goodbye':'z', 'bonjour':'a', 'au revoir':'z', 'how are you':'m'}
How would I split the dictionary into dictionaries (in this case, three dictionaries) with the same values? In the example, I want to end up with this:
dict1 = {'hello':'a', 'bonjour':'a'}
dict2 = {'goodbye':'z', 'au revoir':'z'}
dict3 = {'how are you':'m'}
You can use itertools.groupby to collect by the common values, then create dict objects for each group within a list comprehension.
>>> from itertools import groupby
>>> import operator
>>> by_value = operator.itemgetter(1)
>>> [dict(g) for k, g in groupby(sorted(d.items(), key = by_value), by_value)]
[{'hello': 'a', 'bonjour': 'a'},
{'how are you': 'm'},
{'goodbye': 'z', 'au revoir': 'z'}]
Another way without importing any modules is as follows:
def split_dict(d):
unique_vals = list(set(d.values()))
split_dicts = []
for i in range(len(unique_vals)):
unique_dict = {}
for key in d:
if d[key] == unique_vals[i]:
unique_dict[key] = d[key]
split_dicts.append(unique_dict)
return split_dicts
For each unique value in the input dictionary, we create a dictionary and add the key values pairs from the input dictionary where the value is equal to that value. We then append each dictionary to a list, which is finally returned.
If I have dict like this:
some_dict = {'a': 1, 'b': 2, 'c': 2}
How to get keys that have values 2, like this:
some_dict.search_keys(2)
This is example. Assume some_dict is has many thousands or more keys.
You can do it like this:
[key for key, value in some_dict.items() if value == 2]
This uses a list comprehension to iterate through the pairs of (key, value) items, selecting those keys whose value equals 2.
Note that this requires a linear search through the dictionary, so it is O(n). If this performance is not acceptable, you will probably need to create and maintain another data structure that indexes your dictionary by value.
you can also use dictionary comprehension, if you want result to be dictionary
{ x:y for x,y in some_dict.items() if y == 2}
output:
{'c': 2, 'b': 2}
Well, you can use generator to produce found key values, one by one, instead of returning all of them at once.
The function search_keys returns generator
def search_keys(in_dict, query_val):
return (key for key, val in in_dict.iteritems() if val == query_val)
# get keys, one by one
for found_key in search_keys(some_dict, 2):
print(found_key)
What is the cleanest way to update the values of multiple keys in a dictionary to the values stored in a tuple?
Example:
I want to go from
>>>mydict = {'a':None, 'b':None, 'c':None, 'd':None}
>>>mytuple = ('alpha', 'beta', 'delta')
to
>>>print mydict
{'a':'alpha', 'b':'beta', 'c':None, 'd':'delta'}
Is there an easy one-liner for this? Something like this seems to be getting close to what I want.
EDIT:
I don't wish to assign values to keys based on their first letter. I'm just hoping for something like
mydict('a','b','d') = mytuple
Obviously that doesn't work, but I'm hoping for something similar to that.
If you're trying to create a new dictionary:
d = dict(zip(keys, valuetuple))
If you're trying to add to an existing one, just change the = to .update(…).
So, your example can be written as:
mydict.update(dict(zip('abd', mytuple))))
If you're doing this more than once, I'd wrap it up in a function, so you can write:
setitems(d, ('a', 'b', 'd'), mytuple)
Or maybe a "curried" function that parallels operator.itemgetter?
You could use list comprehension to make it a one-liner, though it's not super efficient.
keys = [ 'a', 'b', 'c', 'd']
values = ['alpha', 'beta', 'delta']
dictionary = dict([(k,v) for k in keys for v in values if v.startswith(k)])
print dictionary #prints {'a': 'alpha', 'b': 'beta', 'd': 'delta'}
Assuming the association key <-> value is the first letter of the value is the first letter of the key.
dict( (v[0],v) for v in mytuple if v[0] in mydict)
I would avoid one-liners in this case. It makes code more readable.
for t in mytuple:
if t[0] in mydict.keys():
mydict[t[0]] = t
If you want to add mytuple items even if the key does not exist, simply remove the if statement.