Create dictionary using split() operation and list comprehension [closed] - python

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.

Related

Turning Key, Value pairs from a Dictionary into strings [closed]

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

Python group and sum with string as keys [closed]

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) ]

Get the name of the dictionary that contains the given key in python [closed]

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}

Combining two list to make a dictionary [closed]

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 8 years ago.
Improve this question
I need to convert two list into a dictionary. I have two list named A and B,
A = [[1,2,3] [2,3,4] [1,4,5] [1,3,4]]
the values in A (list of list) will be unique
B = [[10,13,23] [22,21,12] [5,34,23] [10,9,8]]
the length of both list will be same
I need the result like
C = [['1' :10 , '2' :13, '3': 23] ['2':22, '3':21, '4':12] ['1':5, '4':34, '5':23] ['1':10, '3':9, '4':8]]
I tried the dict method but it is throwing me an error saying list is un hashable type. Please let me know how to do this. Im new to python.
It's hard to be sure, but I'm guessing your problem is this:
If a and b were just flat lists of numbers, all you'd have to do is this:
dict(zip(a, b))
And I'm assuming that's similar to what you wrote. But that doesn't work here. Those aren't lists of numbers, they're list of lists. And you don't to get back a dict, you want a list of dicts.
So, you're asking Python to create a dict whose keys are the sub-lists of a, and whose values are the sub-lists of b. That's an error because lists can't be keys, but it wouldn't be useful even if that weren't an issue.
To actually do this, you need to not only zip up a and b, but also zip up their sublists, and pass those sub-zips, not the main zip, to dict. Like this:
[dict(zip(suba, subb)) for (suba, subb) in zip(a, b)]
I think you want C to be a list of dictionaries. Here's a straightforward way to do that.
def combine(keys, values):
"generate a dictionary from keys and values"
out = {}
for k,v in zip(keys,values):
out[k] = v
return out
def combine_each(keys, values):
"for each pair of keys and values, make a dictionary"
return [combine(klist, vlist) for (klist,vlist) in zip(keys,values)]
C = combine_each(A,B)
Alternative:
>>> A = [[1,2,3], [2,3,4], [1,4,5], [1,3,4]]
>>> B = [[10,13,23], [22,21,12], [5,34,23], [10,9,8]]
>>> [{k:v for k, v in zip(sa, sb)} for (sa, sb) in zip(A, B)]
[{1: 10, 2: 13, 3: 23}, {2: 22, 3: 21, 4: 12}, {1: 5, 4: 34, 5: 23}, {1: 10, 3: 9, 4: 8}]

Finding string in dictionary key where the string is not exactly the key in the dict [closed]

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

Categories