Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a dictionary and a string template that I need to fill in with the key, value pairs from the dictionary.
For example, if the dictionary was {'a':'1', 'b':'2'} then I need the string template (key is in value) to read as: "a is in 1" and "b is in 2"
And I need to iterate through the dictionary and apply each key, value pair into the string template.
Here you go. Simply iterate the key, value pairs and format your template.
mydict = {'a':'1', 'b':'2'}
for key, value in mydict.items():
print('{} is in {}'.format(key, value))
Output:
a is in 1
b is in 2
If you would like to get a list of formated strings just do:
mylist = ['{} is in {}'.format(key, value) for key, value in mydict.items()]
mylist will be ['a is in 1', 'b is in 2'].
You can use the following function:
def fill(d, template):
s = ""
for k, v in d.items():
s += f"{k} {template} {v}\n"
return s[:-1]
>>> d = {'a':'1', 'b':'2'}
>>> print(fill(d, 'is in'))
a is in 1
b is in 2
Note that this will only preserve order in python 3.6+.
dictionary = {'a':'1', 'b':'2'}
template = '{} is in {}'
for key, value in dictionary.items():
print(template.format(key, value))
will do the trick
You could be fancy and use itertools.starmap:
from itertools import starmap
d = {'a': '1', 'b': '2'}
list(starmap('{} is in {}'.format, d.items()))
# ['a is in 1', 'b is in 2']
You can also use an f-string for python 3.5+:
d = {'a': '1', 'b': '2'}
print('\n'.join(f'{k} is in {v}' for k, v in d.items()))
a is in 1
b is in 2
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Python dictionnary:
I need to regroup the keys and add the values accordingly.
For example:
dict = {'A01':6,'A02':5,'A03':2,'B01':2,'B02':3,'B03':2}
new_dict --> {'A':13,'B':7}
You can try this.
>>> dct={'A01':6,'A02':5,'A03':2,'B01':2,'B02':3,'B03':2}
>>> new={}
>>> for k,v in dct.items():
... new[k[0]]=new.get(k[0],0)+v
...
>>> new
{'A': 13, 'B': 7}
Using defaultdict(int)
>>> from collections import defaultdict
>>> new=defaultdict(int)
>>> for k,v in dct.items():
... new[k[0]]+=v
...
>>> new
defaultdict(<class 'int'>, {'A': 13, 'B': 7})
Something like this may work
new_dict = {}
for key, val in dict.items():
new_key = key[0]
if new_key not in new_dict:
new_dict[new_key] = 0
new_dict[new_key] += val
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Beginners question...
If possible without pandas, I'd like to sum up groups within a list or an array.
Input:
Input = [["A",0.2],["B",0.5],["A",0.6],["C",0.1],["B",0.9]]
Desired Output:
Output = [["A",0.8],["B",1.4],["C",0.1]]
Thanks!
You could sum over equal keys by using a dictionary. If you really need, you still can recreate the result to a list of lists via a list comprehension:
lst = [["A",0.2],["B",0.5],["A",0.6],["C",0.1],["B",0.9]]
d = dict()
for sl in lst:
d[sl[0]] = d.get(sl[0], 0) + sl[1]
res = [[k, v] for k, v in d.items()]
You can by doing this:
from collections import defaultdict
sums = defaultdict(lambda: 0)
for arr in input:
sums[arr[0]] += arr[1]
output = [[key, value] for key,value in sums.items()]
This way seems the most idiomatic for me. Following the convention of Python, you should name your variables with lower case and underscore. You can learn more about the defaultdict here: https://docs.python.org/3.6/library/collections.html
You can use this :
Dict = {group[0]: 0 for group in Input}
for group in Input: Dict[group[0]] += group[1]
Output = [[group, value] for group, value in Dict.items()]
A dict can only have unique keys, so we solve half of the problems. To start, each value of each key will be 0.
Next, we iterate through Input and add each value to its corresponding key in our Dict. So now, our job is almost done.
We only have to convert it to the form you want, using a comprehension list.
I would recommend going for a dict as shown hereunder:
inp = [["A",0.2],["B",0.5],["A",0.6],["C",0.1],["B",0.9]]
#create an empty dict
out = {}
#for each element of the inp list
for a in inp:
#if the key does already exist in the dict, you sum the current value
#with what was found in the array at this iteration
if a[0] in out:
out.update({a[0]:a[1]+out.get(a[0])})
#you create a new pair (new key, new value) extract from inp
else:
out.update({a[0]:a[1]})
print out
#if you really need a nested list as output you can convert back the dict
#into a list of list
res = [[key, val] for key, val in out.items()]
print res
output:
{'A': 0.8, 'C': 0.1, 'B': 1.4}
[['A', 0.8], ['C', 0.1], ['B', 1.4]]
This should work:
Output = [ [k,sum(a[1] for a in Input if a[0] == k)] for k in set(a[0] for a in Input) ]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want to create 'dictionary' using `list comprehension':
a_list = ['1, Lastoŭski', '2, Kupala', '3, Kolas']
What I have tried so far is:
d = {key: value for (key, value) in s.split(',') for s in a}
>>> NameError: name 's' is not defined
But this is completely wrong. Could you help me?
as pointed out by #Delgan, it can be done directly via
d1 = dict(keyval.split(", ") for keyval in a_list)
without the inner nesting :)
older approach which were not really correct :-
d = [a.split(',') for a in a_list]
d1 = {key: val for key,val in d}
or
d1 = {key: val for key,val in (a.split(',') for a in a_list)}
No need for a dictionary comprehension. You're making something more complex than it needs to be ;).
a_list = ['1, Lastoŭski', '2, Kupala', '3, Kolas']
d = {}
for i in a_list:
temp = i.split(', ')
d[temp[0]] = temp[1]
print d
# returns: {'3': 'Kolas', '2': 'Kupala', '1': 'Lastoŭski'}
If you need a list comprehension, then this will suffice:
d = dict((key, value) for key, value in [i.split(', ') for i in a_list])
You were close, but you were missing brackets
Try this:
d = dict(map(str, x.split(',')) for x in a_list)
This would help.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
a = {'name1':'tom'}
b = {'name2':'harry'}
c = {'name3':'peter'}
For a given key, I would like to get the name of the dictionary contains it.
Example:
If i give 'name2', I would like to get b as the result
Thanks
You can use next to return the next value in a sequence, and filter it based on some criteria:
key = 'name2'
found = next(d for d in (a, b, c)
if key in d)
a = {'name1':'tom'}
b = {'name2':'harry'}
c = {'name3':'peter'}
name = 'name2'
for k, v in locals().copy().items():
if isinstance(v, dict):
if name in v:
print('"{}" contains id dict "{}"'.format(name, k))
# "name2" contains in dict "b"
But usually you shouldn't do it. Create dict of dicts and iterate through it:
ds = {
'a': {'name1':'tom'},
'b': {'name2':'harry'},
'c': {'name3':'peter'},
}
name = 'name2'
for k, v in ds.items():
if name in v:
print('"{}" contains id dict "{}"'.format(name, k))
# "name2" contains in dict "b"
Let's say that you put references to your dictionaries in an iterable
l = [da, db, dc, ...]
that you initialize the reference to one of your dictionaries to an invalid value
d = None
to find which dictionary has word as a key it's simply
for _ in l:
if word in _:
d = _
break
at this point, either you didn't find word in any of your dicts and d is hence still equal to None, or you've found the dictionary containing word
and you can do everything you want to it
if d:
...
Since you said you would like to get b back as a variable, one way I can think of doing this is making a list of your dictionaries and enumerating through them.
a = {'name1':'tom'}
b = {'name2':'harry'}
c = {'name3':'peter'}
name = 'name2'
dicts = list(a,b,c)
required_dic = findDict(dicts)
def findDict(dicts):
for obj in dicts:
if "name2" in obj:
return obj
but as #germn said, a better idea would be to create a nested dictionary.
You may create a mapping dict, which maps the key to variable binding:
{"name1" : a, "name2" : b, "name3" : c}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to find the key when searching a dictionary list of keys. But the string is not an exact match to the dictionary keys. This is what i have so far:
if string in d.keys():
print 'found'
I would like the key that was found.
I don't think there is anything better than a linear scan across d's keys.
print [k for k in d if string in k]
If this is something your program relies on a lot, you could do this:
class ApproxDict(dict):
def __contains__(self, item):
# item contains the key. Do what you need with it.
return True # or False again this depends on what you want
Using either of the other solutions suggested to implement the __contains__() method.
That way you have your customized lookup and retain the readability of python.
For key substring lookup as you precised in your comment:
>>> class ApproxDict(dict):
... def __contains__(self, item):
... for key in self.keys():
... if item in key:
... return True
... return False
...
>>> d = ApproxDict()
>>> d['abc123'] = "some value"
>>> 'bc1' in d
True
>>> 'bc2' in d
False
>>>
See the python data model documentation.
Hope that helps.
By the way, with a dictionnary:
if key in d:
# whatever
is equivalent to:
if key in d.keys():
# whatever
Let's say that distance compares two strings and returns a lower number if the strings are a good match and a higher number when the strings are a bad match. (You have to decide what to employ there, Levenshtein, etc).
bestMatch = None
value = None
for k, v in d.items ():
match = distance (k, searchedKey)
if bestMatch == None or bestMatch > match:
bestMatch = match
value = v
print (value) # the value of the best matched key
If I'm understanding your question correctly, you want to fuzzy string match with the keys. Here's what I suggest:
>>> keys = ["apple", "plum", "pear", "carrot"]
>>> d = {key:val for key, val in zip(keys,range(4))}
>>> d
{'plum': 1, 'carrot': 3, 'pear': 2, 'apple': 0}
>>>
>>> searchKey = "aple"
>>>
>>> import difflib
>>>
>>> try:
... searchVal = d[searchKey]
... except:
... closeKey = difflib.get_close_matches(searchKey, d.keys(), 1)[0]
... searchVal = d[closeKey]
...
>>> searchVal
0