How to find the similarities for set and print the value - python

I hope to make a dictionary and a list into set then if a.keys() == b then I will print the a.values().
Example:
c = [{'1': '0'}, {'0': '5'},{'2': '0'}]
d = {1,2}
I hope to make these two into the set. Then find all the similarities and print the values without changing the sequence.
Example, I want to print this.
{'1': '0'}
{'2': '0'}
Is it possible to use set?
Below is my code:
a = set(c.keys()) & set(d)
print(a)
for x in a:
y,z = c[x]

Since your example set contains integers while the keys in your example dicts are strings, you should convert the integers in the set to strings first. After that you can simply loop through each dict in the list and if the keys of the dict intersects with the set, then print the dict since it's a match:
d = set(map(str, d))
for i in c:
if i.keys() & d:
print(i)
This outputs:
{'1': '0'}
{'2': '0'}

First of all, you specified your input values the wrong way. The dictionary c should be defined as a dictionary with keys and values and not as a list of dictionaries with one item each - as you did. The keys should be specified as integer and not as string. Otherwise you need to cast them from string to int later on. The second item d is specified the wrong way, too. This should be a list of integers and not a dictionary.
Here's the code that specifies the input values correctly and gives you the desired output:
c = {1: '0', 0: '5', 2: '0'}
d = [1,2]
distinct_keys = c.keys() & set(d)
# {1, 2}
distinct_values = {key: value for key, value in c.items() if key in distinct_keys}
# {1: '0', 2: '0'}
distinct_values
This gives {1: '0', 2: '0'} as output.

Related

Appending dictionary to list with different value same key

I have a list of dictionaries, that have same keys and some have different values for those keys. I am trying to append the dictionaries that have different values from the list to keep track of the different values and I would concatenate the values of other keys. For example, I am storing 'a' keys with same values and concatenating the 'b' values that have same 'a':'1'
input list: d = [{'a': '1', 'b': '3'}, {'a': '2', 'b': '4'}, {'a': '1', 'b':'5'}]
output list: p = [{'a':'1', 'b': '35'}, {'a': '2', 'b': '4'}]
So far, I tried the following code, but it doesnt recognize the different values
length = len(p)
j = 0
for i in d:
while j < length:
if p[j]['a'] is not i['a']:
p.append({'a', p[j]['a']})
else:
p[j]['b'] += i['b']
j += 1
j = 0
any tips would be appreciated
Use a dictionary that has the a values as its keys so you don't have to loop through the result list for a matching a.
temp_dict = {}
for item in d:
if item['a'] in temp_dict:
temp_dict[item['a']]['b'] += item['b']
else:
temp_dict[item['a']] = item.copy()
p = list(temp_dict.values())

Sort a python dictionary based on input value?

I have a dictionary with four keys a,b,c,d with values 100,200,300,400
list1 = {'a':'100','b':'200','c':'300','d':'400'}
And a variable inputs.
inputs = 'c'
If inputs is c. The list1 dictionary has to be sorted based on it.
inputs = 'c'
list1 = {'c':'300','a':'100','b':'200','d':'400'}
inputs = 'b'
list1 = {'b':'200','a':'100','c':'300','d':'400'}
In Python3.7+ dict keys are stored in the insertion order
k ='c'
d={k:list1[k]}
for key in list1:
if key!=k:
d[key]=list1[key]
Output
{'c': '300', 'a': '100', 'b': '200', 'd': '400'}
Seems like you just want to rearrange your dict to have the chosen value at the front, then the remaining keys afterwards:
dict1 = {'a':'100','b':'200','c':'300','d':'400'}
key = 'c'
result = {key: dict1[key], **{k: v for k, v in dict1.items() if k != key}}
print(result)
# {'c': '300', 'a': '100', 'b': '200', 'd': '400'}
The ** simply merges the leftover filtered keys with key: dict1[key].
If you just want to change the position to the first one a given value if it exists, it could be done in the following way:
list1 = {'a':'100','b':'200','c':'300','d':'400'}
inputs = 'c'
output = {}
if inputs in list1.keys():
output[inputs] = list1.get(inputs)
for i in list1.keys():
output[i] = list1[i]
Output;
{'c': '300', 'a': '100', 'b': '200', 'd': '400'}
Here's a one-liner:
d = {'a':'100','b':'200','c':'300','d':'400'}
i = input()
d = {i:d[i],**{k:d[k] for k in d if k!=i}}
print(list1)
Input:
c
Output:
{'a': '100', 'b': '200', 'd': '400', 'c': '300'}

How to assign the values for dict(keys and values) into a new list? and also how to print the keys and values in the string dictionary?

I would like to print the keys and values of a string of dictionaries. For example,
a = [{'1': '0'}, {'9': '2'}, {'4': '3'}, {'3': '5'}, {'0': '7'}, [], [], [], []]
I tried this :
for x in a:
for y in x.values():
print(y)
not working
for x in a:
for y in x.itervalues():
print(y)
not working
for x in a:
for y in x.items():
print(y)
not working
Anyway to print it like this? :
1 0
9 2
4 3
3 5
0 7
or
keys = 1,9,4,3,0
values = 0,2,3,5,7
One possible solution is to filter out non-dictionaries using list comprehension, then convert the dictionaries into key-value tuples, and separate the keys and values with zip:
k,v = zip(*[list(x.items())[0] for x in a if isinstance(x, dict)])
print(k,v)
#('1', '9', '4', '3', '0') ('0', '2', '3', '5', '7')
And if you want the side by side key/value pair output, then you can do something like this (code would need to be altered if any of your dictionaries were going to contain more than one key/value pair):
for x in a:
if isinstance(x, dict):
# "if isinstance" is here just to ignore the lists in your list,
# you may want to do something else with those
print(x.keys(), x.values())
# (['1'], ['0'])
# (['9'], ['2'])
# (['4'], ['3'])
# (['3'], ['5'])
# (['0'], ['7'])
If you need to handle more than one key/value pair in the dictionary items and print just the values (minus the formatting), then something like this:
for x in a:
if isinstance(x, dict):
tups = x.items()
for tup in tups:
print('{} {}'.format(tup[0], tup[1]))
# 1 0
# 9 2
# 4 3
# 3 5
# 0 7

Python pop dictionary list values

I have a dictionary:
{'dict': [['IE', '5', '-5'], ['UK', '3', '-9']]}
I wish to pop the list values that are outside of the UK, therefore taking the first value within the lists and comparing to see if it is equal to 'UK'.
I currently have:
for k,v in insideUK.items():
for i in v:
if i[0] == "UK":
print(x)
else:
k.pop(v)
I know after the else is wrong but need help!
I wish for the dict to look like this once finished popping values that aren't equal to "UK".
{'dict': [['UK', '3', '-9']]}
You can use a list comprehension to filter out based on the first element
>>> data = {'dict': [['IE', '5', '-5'], ['UK', '3', '-9']]}
>>> {'dict': [i for i in data['dict'] if i[0] == 'UK']}
{'dict': [['UK', '3', '-9']]}
You can also do it using the filter function:
d = {'dict': list(filter(lambda i: 'UK' in i, d['dict']))}
print(d)
Output:
{'dict': [['UK', '3', '-9']]}
A nested dict and list expression can do this:
{k: [i for i in v if i[0] == 'UK'] for k,v in insideUK.items()}
If you really want to do it with a for-loop and change the list in-place, you could do something like this:
for k,v in insideUK.items():
for i in v:
if i[0] == "UK":
print(x)
else:
v.remove(i)
But it is discouraged strongly to change the list you are iterating over during the iteration

Selecting K largest values in a dictionary of dictionary in python

I have a dictionary of dictionary as below:
ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}]
I would like to select k-largest values with their keys for each key of dictionary (ls). I have written below commands. It just gives me the k-largest keys without their values.
Python Code:
import heapq
k=2
for dic in ls:
for key in dic:
print(heapq.nlargest(k, dic[key], key=dic[key].get))
Output
['2', '3']
['3', '1']
I need to have value of each selected key.
First of all, I just wanted to check why you have
ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}]
This is a list containing a dict, which doesn't match your description in the question.
Here is a solution that uses dict comprehensions that should give you what you want :)
def get_n_largest_vals(n, d):
x = {key: heapq.nlargest(len, map(int, d[key])) for key in d}
return {key: map(str, x[key]) for key in x}
Here it is being used for your problem:
ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}]
d = ls[0]
get_n_largest_vals(2, d)
>>> {'0': ['3', '2'], '1': ['3', '2']}
How about:
from operator import itemgetter
for d in ls:
for key, d2 in d.items():
print(dict(heapq.nlargest(k, d2.items(), key=itemgetter(1))))
Notice that your values are still strings so they'd be lexically ordered, which is not what you want, because '2' > 12' And the dictionary is not ordered!

Categories