matching and joining key/val of dictionaries in list [closed] - python

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
this is a list, I got lists like this :
k = [{a:1}, {b:2}, {c:3}, {d:4}, {a: 5}] and t = [{a:6}, {b:7}, {c:8}, {d:9}, {a: 10}]
if a's dictionary key in k is matching with t's dictionary key in t, then extract value and key in dictionary
and then I want to reorganize like below:
newlist = [a is 1 and 6, b is 2 and 7, c is 3 and 8, d is 4 and 9, a is 5 and 10]

From your description, it is little hard to understand what you require exactly, but I have done my best to obtain what I think you need! :-)
k = [{'a':1}, {'b':2}, {'c':3}, {'d':4}, {'a': 5}]
t = [{'a':6}, {'b':7}, {'c':8}, {'d':9}, {'a': 10}]
newlist = []
for i in range(min(len(k), len(t))):
letter_k, value_k = [*k[i].items()][0]
letter_t, value_t = [*t[i].items()][0]
if letter_k == letter_t:
newlist.append({letter_k: [value_k, value_t]})
This will yield:
newlist = [{'a': [1, 6]}, {'b': [2, 7]}, {'c': [3, 8]}, {'d': [4, 9]}, {'a': [5, 10]}]
Note that I did not combine the dictionaries due to duplicate keys!

Related

How to sort a dictionary by the frequency of its values [duplicate]

This question already has answers here:
How to sort a Python dictionary by value? [duplicate]
(2 answers)
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
How do you sort a dictionary by the frequency of its values in Python? For example, if I have a dictionary:
{'apples': 2, 'oranges': 5, 'bananas': 2, 'corn': 1, 'tangerines': 2, 'popsicles': 5}
How can I get it to return:
{'apples': 2, 'bananas': 2, 'tangerines': 2, 'oranges': 5, 'popsicles': 5, 'corn': 1}
EDIT:
Upon closer inspection, the only answer currently given does not answer this question. The answer sorts the dictionary according to the "size" of the values and not the frequency with which the values occur. Also, the answer that is linked also does not answer this question. Like the only answer currently given, the question linked is about sorting dictionaries according to the size of the values, not the frequency with which the values occur
Try this:
data = {'apples': 5, 'oranges': 2, 'bananas': 5, 'corn': 1, 'tangerines': 5, 'popsicles': 2}
{j: i for j, i in sorted(data.items(), key=lambda item: item[1], reverse=True)}

How to find the count of numbers that are less than each element of a list [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 8 months ago.
Improve this question
I have a list [1,2,3,4,5,6,7], for each element in the list, I need to find the count of a number of elements that are less than the number. For example, the first element is 1 and there are 0 elements in the list that are less than 1, the second number is 2 and there is 1 element less than 2. So basically the output should be [0,1,2,3,4,5,6]. Need to do this in Python. Any help would be appreciated. Below is the code I've tried,
lst = [1,2,3,4,5,6,7]
count = 0
final = []
for i in range(len(lst)):
for j in range(i+1,len(lst)):
if lst[i] < lst[j]:
count = count + 1
final.append(count)
print (final)
Below is the output I got,
[6, 11, 15, 18, 20, 21, 21]
Try:
lst = [1, 2, 3, 4, 5, 6, 7]
out = [sum(vv < v for vv in lst[:i]) for i, v in enumerate(lst)]
print(out)
Prints:
[0, 1, 2, 3, 4, 5, 6]

Subdivide python dict [duplicate]

This question already has answers here:
How do I create a nested dict from a dict by splitting the keys on a delimiter in python?
(4 answers)
Closed 1 year ago.
I want to write a method which takes a dict in the form of {a: 1, b-c: 2, b-d: 3, e-f-g: 4} and returns {a: 1, b: {c: 2, d: 3}, e: {f: {g: 4}}}. Basically split the keys containing - into subdicts. I've tried to do it iteratively and recursively but I got stuck. Any tips?
You can use collections.defaultdict with recursion:
from collections import defaultdict
d = {'a': 1, 'b.c': 2, 'b.d': 3, 'e.f.g': 4}
def group(d):
nd = defaultdict(list)
for [a, *b], c in d:
nd[a].append([b, c])
return {a:b[0][-1] if not any(j for j, _ in b) else group(b) for a, b in nd.items()}
result = group([[a.split('.'), b] for a, b in d.items()])
Output:
{'a': 1, 'b': {'c': 2, 'd': 3}, 'e': {'f': {'g': 4}}}

How to add values from different dict based on their key [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 6 years ago.
Improve this question
For example I have two dicts:
a = {'a':1,'b':0, 'c':5}
b = {'d':4,'a':2}
While update() function can refresh old values, like
a.update(b)
will return
{'a': 2, 'b': 0, 'c': 5, 'd': 4}
but I want to have their sum, in other words, I want to have
{'a': 3, 'b': 0, 'c': 5, 'd': 4}
so the value of 'a' is the sum of both dict
How can I do that?
Following code will update a the way you want:
a = {'a': 1, 'b': 0, 'c': 5}
b = {'d': 4, 'a': 2}
for k, v in b.iteritems():
a[k] = a.get(k, 0) + v
print a # {'a': 3, 'c': 5, 'b': 0, 'd': 4}
collections.Counter might give you what you want. The documentation for collections.Counter.update() says:
Like dict.update() but adds counts instead of replacing them.
from collections import Counter
a = Counter({'a':1, 'b':0, 'c':5})
b = {'d':4, 'a':2}
a.update(b)
print a
Result:
Counter({'c': 5, 'd': 4, 'a': 3, 'b': 0})

Double for loop in a dictionary 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 9 years ago.
Improve this question
I have a dictionary with keys from 1 to N. I would like to go through this dictionary with a double for loop so that I don't take two elements at the same time (k goes from 1 to N-1 and j from k+1 to N). I need to this efficiently as I will have to repeat this operation. Is there anyway to do a dictionary comprehension so as to go through the keys as: k goes from 1 to N-1 and j from k+1 to N?
If the order of the keys don't matter, you can do it like this
my_dict = {"a": 1, "b": 2, "c": 3, "d": 4}
from itertools import combinations
for key1, key2 in combinations(my_dict.keys(), r = 2):
print key1, key2
Output
a c
a b
a d
c b
c d
b d
By your description, it sounds like you're trying to access the upper triangle of (what should be) an array, so you can use numpy's triu(http://docs.scipy.org/doc/numpy/reference/generated/numpy.triu.html).
As others have said, using a dictionary is probably not the best choice.
On "What I want to do is go through all the couples of objects in the dictionary and compute the distance between them"
You can use numpy broadcasting to calculate the distances, it's fast:
In [175]: locs=np.array([1,2,4,6])
In [176]: np.abs(locs[:, None]-locs)
Out[176]:
array([[0, 1, 3, 5],
[1, 0, 2, 4],
[3, 2, 0, 2],
[5, 4, 2, 0]])
and you can use the index e.g., locs[0][3] to get distance between element 0 and element 3 directly.

Categories