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)
Related
Am trying to combine a dictionary and a list which has dictionaries and an empty dictionary
dict1 = {'a': 1, 'b': 2}
list1 = [{'c': 3}, {'d':4}]
emptydict = {}
emptylist = []
Trying to merge and make it a final dictionary which looks like below.
final = {'a': 1, 'b': 2, 'c': 3, 'd':4}
Code:
final = {**dict1, **list1[0], **list1[1], **emptydict, **emptylist}
Here I dont know the length of list1, can anyone suggest me a better way than this ?
dict.update updates an existing dictionary. Unfortunately it’s a mutating method that does not return a value. Therefore adapting it to functools.reduce requires a wrapper.
Due to this, I’d be tempted to use a good old loop:
final = dict(dict1)
for d in list1:
final.update(d)
But for completeness, here’s a way using functools.reduce:
import functools
def dict_update(d, v):
d.update(v)
return d
final = functools.reduce(dict_update, list1, dict1.copy())
If you are using python 3.3+, you can use ChainMap to merge list of dicts into a single dict. And then use ** operator to merge dict1 and dict(ChainMap(*list1)).
from collections import ChainMap
final = {**dict1, **ChainMap(*list1)}
I have a Json list and I want to print all the keys from a given key till the end of dictionary. But the code I wrote is very complex. How to do it with less complexity ?
I'm using Python 3
dictionary = [{"a": "1"}, {"b": "2"}, {"c": "3"}, {"d": "4"}]
try:
for token in dictionary:
if "b" in list(token.keys())[0]:
new_dict = dictionary[len(list(token.keys())[0]):]
for i in new_dict:
print(new_dict[len(list(i.keys())[0]):])
break
else:
print("Inception")
except Exception as error:
print(str(error))
DESIRED
Input: b
Output: c, d
My Output:
Inception
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
Use itertools.dropwhile() to skip all dictionaries that don't have a 'b' key:
from itertools import dropwhile
filtered = dropwhile(lambda t: 'b' not in t, dictionary)
next(filtered) # skip the dictionary with `b` in it.
for token in filtered:
print(token)
This prints all dictionaries after the first. If you only need to print their keys, do so explicitly:
filtered = dropwhile(lambda t: 'b' not in t, dictionary)
next(filtered) # skip the dictionary with `b` in it.
for token in filtered:
print(*token, sep='\n')
This prints the keys on separate lines; if there is just one key, then that's all that'll be printed for each token dictionary.)
As a side note: you really do not want to use list(dict.keys())[0]. Before Python 3.6, dictionaries have no set order (instead being subject to insertion and deletion history and the current random hash seed), so if you have more than one key what value you'll get is a gamble. And all you want to do is see if a key is present, so use a key in dictobject membership test.
To get the first key out of each dictionary, I'd use next(iter(dictobject)), avoiding creating a list:
first_key = next(iter(dictobject))
I'd only use this if I had single-key dictionaries. I'd also avoid using dictionaries for such a scenario; perhaps you really wanted to use an ordered dictionary instead (in Python < 3.6, use collections.OrderedDict(), otherwise use the regular dict type).
This is one way. The idea is to find the index of the dictionary with desired key. Then filter your list accordingly.
keys = [next(iter(x)) for x in dictionary]
res = keys[keys.index('b')+1:]
# ['c', 'd']
You can re-write your code as follows for your desired result.
found = False
for data in dictionary:
if found:
print(list(data.keys())[0])
if 'b' in data.keys():
found = True
I have a dictionary in which one key is a NaN, and I want to delete the key and its corresponding value. I have tried this:
from math import isnan
clean_dict = filter(lambda k: not isnan(k), dict_HMDB_ID)
but the clean_dict is not a dictionary. I want to output it from python, but I get ''
filter doesn't return a dictionary. It returns a list in Python 2 and a filter object in Python 3.
You can use dict.pop:
d = {'a': 1, 'b': 2}
print(d)
# {'a': 1, 'b': 2}
d.pop('b')
print(d)
# {'a': 1}
And in your specific case,
dict_HMDB_ID.pop(float('NaN'))
For the sake of completeness. it could be done with a dictionary comprehension but there is no point in iterating since keys are unique anyway
clean_dict = {k: v for k, v in dict_HMDB_ID.items() if not math.isnan(k)}
If you insist on using filter here (you really shouldn't) you will need to:
pass it dict_HMDB_ID.items() so it will keep the original values
provide a custom function because it will now operate on (key, value) tuples.
transform the returned filter object (it will contain an iterator with (key, value) tuples) back to a dictionary
import math
dict_HMDB_ID = {1: 'a', float('Nan'): 'b'}
clean_dict = dict(filter(lambda tup: not math.isnan(tup[0]), dict_HMDB_ID.items()))
print(clean_dict)
# {1: 'a'}
I should probably mention that the first approach (.pop) directly modifies the dict_HMDB_ID while the other two create a new dictionary. If you wish to use .pop and create a new dictionary (leaving dict_HMDB_ID as it is) you can create a new dictionary with dict:
d = {'a': 1, 'b': 2}
new_d = dict(d)
new_d.pop('b')
print(d)
# {'b': 2, 'a': 1}
print(new_d)
# {'a': 1}
you could do:
from math import nan
dict_HMDB_ID.pop(nan)
clean_dict = dict_HMDB_ID
or the other way around if you wna to preserve dict_HMDB_ID
from math import nan
clean_dict = dict(dict_HMDB_ID)
clean_dict.pop(nan)
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.
I am searching for periods "." in a dictionary and trying to delete the key/value pair if I find it
if "." in dict.values():
#delete key, value pair from the dictionary
I am sure this is very simple but I cannot seem to locate an explanation.
Thanks for your help.
Create a new dictionary without those unwanted values using dictionary comprehension. Here is an example of how to do it:
>>> old_dict = {'one': '.', 'two': 2, 'three':3, 'four':'.'}
>>> new_dict = {k:v for k,v in old_dict.iteritems() if not v == '.'}
>>> new_dict
{'three': 3, 'two': 2}
using iteritems instead of items avoids creating an intermediate list and improves performance.
If you don't want to copy your dictionary, (for example if the dictionary is large, or you have a reference to it elsewhere) then you should do it this way:
ks = [k for k in d if d[k]=='.']
for k in ks:
d.pop(k)
Create your list of keys to be removed ahead of time as shown above. You don't want to modify your dictionary while iterating over it.