Python 3: How to compare two tuples and find similar values? - python

I have two dictionaries: (1)Inventory and (2)Items
Under these dictionaries are tuples which are added using user's input.
dict_inventory = {('fruits', ['apple','mango'])
dict_items = {('apple', [3, 5])
('mango', [4, 6])}
How do I compare the two and to match similar values which are apple and mango
My code is not printing anything:
for itemA in dict_inventory.values():
for itemB in dict_items.keys():
if itemA == itemB:
print("Match!")

Your original for-loop was getting the values from the inventory dictionary as a list rather than a string when you iterated through the values. Since it returned a list, you will need to iterate through those values as well. This should get you running:
inventory = {
"fruits": ["apples", "mangos",]
}
items = {
"apples": [3, 5],
"mangos": [4, 6],
}
for value in inventory.values():
for item_a in value:
if item_a in items.keys():
print("Match!")
However, you could just merge the two dictionaries.
inventory = {
"fruits": {
"apples": [3, 5],
"mangos": [4, 6],
}
}

Related

Compare the keys of two nested dictionaries with level 3

I have two nested dictionary: main and test. I want to compare the keys of the dictionaries and find the difference.
main = {"A":{"AA":{"AAA1": [1, 3], "AAA2": [2,4]}, 'BB': {'BBB1': [2 ,4 ], 'BBB2': [5,7]}}}
test1 = {"A":{"AA":{"AAA1": [3, 3], "AAA2": [4,4]}, 'BB': {'BBB1': [4 ,4 ], 'BBB2': [7,7]}}}
test2 = {"A":{"AA":{"AAA1": [3, 3], "AAA2": [4,4]}, 'BB': {'BBB1': [4 ,4 ]}}}
When comparing main and test1, the expected output is {} as all keys till level 3 are present.
When comparing main and test2, the expected output is {'A': {'BB': ['BBB2']}}.
I have tried the solution for three levels using the How to get the difference between two dictionaries in Python? Is there any other efficient method for nested dictionaries? Thanks in advance.

how to create a dictionary having different number of values at different keys?

Question.1 ) I want to create a dictionary , it consist of 8 keys , some keys has 2 values and some keys have 3 values. how to create this kinda dictionary in python.
i been trying using nested loops , but my logic didn't worked.
Desired output
dict_a = { 1:[0,1], 2:[2,3], 3:[4,5], 4:[6,7], 5:[8,9], 6:[10,11], 7:[12,13,14], 8:[15,16,17] }
Question.2 ) If we successfully create the dict_a then, In the second part, i want to merge the multiple values of dict_a according to the dict_b,shown below.
for example :- In dict_b = { 1:[1,2], 2:[2,3]......} ,Here 1:[1,2] means I want to merge 1st and 2nd 'values' of dict_a dictionary, which will give me [0, 1, 2, 3]. similarly 2:[2,3] will give me [2,3,4,5]
dict_b = { 1:[1,2], 2:[2,3], 3:[3,4], 4:[4,5], 5:[5,6], 6:[6,7], 7:[7,8] }
I actually tried the above method successfully, but for two keys 7thand 8th in dict_a , i want to merge with first two values only, i.e when dict_b goes to it's 7th key 7:[7,8], i want the result to be [12,13,15,16] and not [12,13,14,15,16,17].
but the method i used below will merge all inevitably.
dict_a = { 1:[0,1], 2:[2,3], 3:[4,5], 4:[6,7], 5:[8,9], 6:[10,11], 7:[12,13,14], 8:[15,16,17] }
dict_b = { 1:[1,2], 2:[2,3], 3:[3,4], 4:[4,5], 5:[5,6], 6:[6,7], 7:[7,8] }
a_list = []
for i in dict_b:
tem = []
a_list.append(tem)
for j in dict_b[i]:
tem.extend(dict_a[j])
print(tem)
Desired output-
[0, 1, 2, 3]
[2, 3, 4, 5]
[4, 5, 6, 7]
[6, 7, 8, 9]
[8, 9, 10, 11]
[10, 11, 12, 13]
[12, 13, 15, 16]
If you only want to merge with the first 2 values, use a slice.
Change
tem.extend(dict_a[j])
to
tem.extend(dict_a[j][:2])

Can't get the size of numpy.ndarray

I have a dataframe as follows:
version count region listing
2 v2 2 CAN [7, 8]
2 v3 3 CAN [7, 8, 9]
I want to extract listing list for each row and get the length. So I did the following:
group_v2_list = group[group['version'] == 'v2']['listing'].values
and I get output as [list([7, 8])]. Here the type of listing column is numpy.ndarray which I get after using type(group_v2_list).
Now I want to get the number of elements in this group_v2_list but I am unable to get it.
I tried len(group_v2_list) and group_v2_list.size but both are giving me 1. I want to get the number of elements which should be 2 as 7, 8.
How can I get that?
You do not need to access the numpy representation for this.
One way is to use .loc accessor to extract the series and find the length of the first element:
df = pd.DataFrame({'version': ['v2', 'v3'],
'count': [2, 3],
'region': ['CAN', 'CAN'],
'listing': [[7, 8], [7, 8, 9]]})
df_v2_list = df.loc[df['version'] == 'v2', 'listing']
res_v2 = len(df_v2_list[0])
# 2
If there are multiple elements in your filtered data, you can retrieve a list of their lengths by using pd.Series.map(len):
df_v_all_list = df.loc[df['version'].str.startswith('v'), 'listing']
res_all = df_v_all_list.map(len).tolist()
# [2, 3]

Python: Find count of the elements of one list in another list

Let's say I have two lists list1 and list2 as:
list1 = [ 3, 4, 7 ]
list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]
I want to find the count of the elements of list1 which are present in list2.
Expected output is 4 because 3 and 4 from list1 are appearing twice in list2. Hence, total count is as 4.
Use list comprehension and check if element exists
c = len([i for i in list2 if i in list1 ])
Better one from #Jon i.e
c = sum(el in list1 for el in list2)
Output : 4
You may use sum(...) to achieve this with the generator expression as:
>>> list1 = [ 3, 4, 7 ]
>>> list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]
# v returns `True`/`False` and Python considers Boolean value as `0`/`1`
>>> sum(x in list1 for x in list2)
4
As an alternative, you may also use Python's __contains__'s magic function to check whether element exists in the list and use filter(..) to filter out the elements in the list not satisfying the "in" condition. For example:
>>> len(list(filter(list1.__contains__, list2)))
4
# Here "filter(list(list1.__contains__, list2))" will return the
# list as: [3, 3, 4, 4]
For more details about __contains__, read: What does __contains__ do, what can call __contains__ function?.
You can iterate first list and add occurences of a given number to a sum using count method.
for number in list1:
s += list2.count(number);
You can use collections.Counter here, so a naive and rather ugly implementation first (mine).
list1 = [ 3, 4, 7 ]
list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]
from collections import Counter
total = 0
c = Counter(list2)
for i in list1:
if c[i]:
total += c[i]
This doesn't take into account what happens if you've got duplicates in the first list (HT Jon), and a much more elegant version of this would be:
counter = Counter(list2)
occurrences = sum(counter[v] for v in set(list1))

Get a list of values from a list of dictionaries?

I have a list of dictionaries, and I need to get a list of the values from a given key from the dictionary (all the dictionaries have those same key).
For example, I have:
l = [ { "key": 1, "Val1": 'val1 from element 1', "Val2": 'val2 from element 1' },
{ "key": 2, "Val1": 'val1 from element 2', "Val2": 'val2 from element 2' },
{ "key": 3, "Val1": 'val1 from element 3', "Val2": 'val2 from element 3' } ]
I need to get 1, 2, 3.
Of course, I can get it with:
v=[]
for i in l:
v.append(i['key'])
But I would like to get a nicer way to do so.
Using a simple list comprehension (if you're sure every dictionary has the key):
In [10]: [d['key'] for d in l]
Out[10]: [1, 2, 3]
Otherwise you'll need to check for existence first:
In [11]: [d['key'] for d in l if 'key' in d]
Out[11]: [1, 2, 3]

Categories