Getting a specific value of a key in a dictionary? - python

I have a dictionary like this:
d = {'k1':[0.2,0.65,0.23], 'k2':[0.32,1.2,3.3], 'k3':[1.8,0.6,0.4], ...}
So, I want to get a list of the key and the second value of each key in a list. I have tried this code:
names = list(d.keys())
values = list(d.values())
The first line is correct and gives me the list of all keys, but the second line provides all the values, which is not what I needed. So I need only the second or the third value of each key. Any suggestions?

Iterate over the dict and get the v[1] for each key, in a new dict:
d = {'k1':[0.2,0.65,0.23], 'k2':[0.32,1.2,3.3], 'k3':[1.8,0.6,0.4]}
print({k:v[1] for k,v in d.items()})
OUTPUT:
{'k1': 0.65, 'k2': 1.2, 'k3': 0.6}

try:
mylist = [(k, v[1]) for k, v in d.items()]

{k:v[1] for k,v in d.items()}
Create a new dict with the second value from the list-value of the original dict using a dictionary comprehension.

This will help you:
names = list(d.keys())
values = [v[1] for v in d.values()]

This iterate key and values per key
for k,v in d.items():
print("Key: %s" %k)
print("Values: %s" %v)
print("-"*8)

>>> import numpy as np
>>> d = {'k1':[0.2,0.65,0.23], 'k2':[0.32,1.2,3.3], 'k3':[1.8,0.6,0.4]}
>>> np.array(list(d.values()))[:,1]
Output:
array([0.65, 1.2 , 0.6 ])

d = {k1:[0.2,0.65,0.23], k2:[0.32,1.2,3.3], k3:[1.8,0.6,0.4], ...}
for fetching only 2nd element from the values, Below code will print only 2nd elements of each key
example - [v[1] for k,v in d.iteritems()]
prints [0.65,1.2,0.6]
for fetching key:value
{k:v[1] for k,v in d.iteritems()}
prints {'k1':0.65,'k2':1.2,'k3':0.6}
for fetching 2nd and 3rd element both , something like this can be done
{k:[v[1],v[2]] for k,v in d.iteritems()}

Related

Merge values in a list of dictionaries on key

i have that array of dicts:
[{'dog': 'dog-1'}, {'monkey': 'monkey-1'}, {'buffalo': 'buffalo-6'}, {'dog': 'dog-2'},{'pig': 'pig-3'}, {'monkey': 'monkey-6'}, {'monkey': 'monkey-6'}]
And I need to put everyone that has the same key in the same dict. I need that result:
[{'dog': ['dog-1', 'dog-2']}, {'monkey': ['monkey-1', 'monkey-6', 'monkey-6']}, {'buffalo': ['buffalo-6']}, {'pig': ['pig-3']}]
Use a defaultdict:
from collections import defaultdict
lst = [{'dog': 'dog-1'}, {'monkey': 'monkey-1'}, {'buffalo': 'buffalo-6'}, {'dog': 'dog-2'},{'pig': 'pig-3'}, {'monkey': 'monkey-6'}, {'monkey': 'monkey-6'}]
output = defaultdict(list)
for d in lst:
for k,v in d.items():
output[k].append(v)
The general idea is, while you're iterating over the list, you want to know if you've reached a dictionary whose key you've already seen before. If you've already seen that key, then you want to append its value to the value of the matching key; if not, you want to create a new key with a default value (in this case an empty list). You can use dict.setdefault to do that.
out = {}
for d in lst:
for k, v in d.items():
out.setdefault(k, {}).setdefault(k, []).append(v)
out = list(out.values())
Output:
[{'dog': ['dog-1', 'dog-2']},
{'monkey': ['monkey-1', 'monkey-6', 'monkey-6']},
{'buffalo': ['buffalo-6']},
{'pig': ['pig-3']}]

Iterate through list of dictionories and compare with other dictionories

I have the following dictionaries
dic1 = { 'T1': "HI , china" , 'T2': "HI , finland" ,'T3': "HI , germany"}
dic2 = { 'T1': ['INC1','INC2','INC3'] , 'T2': ['INC2','INC4','INC5'],'T3': ['INC2','INC5']}
dic3 = { 'INC1': {'location':'china'} , 'INC2': {'location':'germany'},'INC3': {'location':'germany'},'INC4': {'location':'finland'}}
I need to remove the values in dic2 based on the dic1,dic3
example :
I have to iterate through dic2 first and check the T1 and its INC values.
If the corresponding T1 key value in the Dic1 matches with the corresponding INC values in the dic3 the keep the value in dic2 otherwise pop the value.
Detaileded explanation given in the picture. And I am expecting the following output.
dic2 = { 'T1': ['INC1'] , 'T2': ['INC4'],'T3': ['INC2']}
example code :
for k, v in dic2.items():
for k1, v1 in dic1.items():
if k is k1:
print k
for k2 in v:
for k3 in dic3.items():
I am new to python. I have tried the above pieces of code and I got struck down.Could you please help me out.
Can be done in a one-liner:
>>> {k: [i for i in v if dic3.get(i, {}).get('location', '#') in dic1[k]] for k, v in dic2.items()}
{'T1': ['INC1'], 'T2': ['INC4'], 'T3': ['INC2']}
[i for i in v if dic3.get(i, {}).get('location', '#') is the list comprehension to pick only the values from dic2's lists if dic3[i]['location'] is inside dic1[k], where i is the key in dict d3 and k is the key from dict d2 as well as dict d1.
I used dic3.get(i, {}).get('location', '#') (rather than dic3[i]['location'], you get KeyError for key INC5 which is not in dic3) to avoid the issue of key i not being in dic3 (would return an empty dict for my next .get) and in the second .get, again I use it to return the location key's corresponding value if it exists and check if that returned string lies inside the values of dict d1.
I return # (can be any string/char) if I know that the key i doesn’t exist in dic3 (i not existing will essentially give {}.get('location', '#') which in turn will give #, this is sure to fail the membership in d1, hence it's Ok).
Toned down for-loop version:
>>> ans = {}
>>> for k, v in dic2.items():
... temp = []
... for i in v:
... if i in dic3 and dic3[i]['location'] in dic1[k]:
... temp.append(i)
... ans[k] = temp
...
>>> ans
{'T1': ['INC1'], 'T2': ['INC4'], 'T3': ['INC2']}
From my understanding, you are supposed to modify the original dic2 dictionary rather than creating a new one for your answer, this is what I got:
delete = []
for key, value in dic2.items():
loc = dic1[key][5:]
for inc in value:
if inc not in dic3:
delete.append(inc)
else:
if loc != dic3.get(inc)['location']:
delete.append(inc)
for item in delete:
value.remove(item)
delete = []
print(dic2)
>>> {'T1': ['INC1'], 'T2': ['INC4'], 'T3': ['INC2']}
The first for loop iterates through dic2 and sets the location required to the variable loc. The next one iterates through the lists (values) and adds them to a delete list.
At the end of each loop, it iterates through the delete list, removing each element from the value list, and then setting delete to an empty list.
I am also relatively new to python so I am sure there could be efficiency issues.
This is essentially the same as the other answers but as a one-liner, it may be more readable (maybe not, since it's subjective).
{k: [el] for k, v in dic2.items() for el in v if (el in dic3.keys() and dic3[el]['location'] in dic1[k])}

Check if value of one dictionary is the key for the other

I basically want to check if the value in one dictionary is the key in the other.
So for example, I have two dictionaries
a = {armani: jeans, dolce: gabbana}
b = {jeans: robo, jobs: versace}
I wrote code to do the check such that it only obtains the values that is the key in the other dictionary. So in this case, I just want to display {armani: robo} as jeans was already in both. So like the value of jeans in the second dictionary then becomes the main value in the new final dictionary
This is the code:
{k:v for k,v in a.items() if v in b.items()}
But it doesn't work and I don't know how to do the check to see if the value is the key in another list
This should work:
{k:b[v] for k,v in a.items() if v in b}
You were just missing two elements:
You don't need to write if v in b.items() because Python interprets if v in b as "if v is in the keys of b".
You need to map k not to v itself, but to v's value in b, which is b[v].
Alternatively, you could filter with set intersection.
a = {'armani': 'jeans', 'dolce': 'gabbana'}
b = {'jeans': 'robo', 'jobs': 'versace'}
c = set(a.values()).intersection(b)
d = {k:b[k] for k in c}
# or as a one-liner
e = {k:b[k] for k in set(a.values()).intersection(b)}
It might be faster than looping through the whole dictionary.
I think you need:
a = {"armani": "jeans", "dolce": "gabbana"}
b = {"jeans": "robo", "jobs": "versace"}
res = {k1:v2 for k1,v1 in a.items() for k2,v2 in b.items() if v1 ==k2}
print(res)
Output:
{'armani': 'robo'}

How do I create a dictionary from two lists in python while maintaining all key value information?

Example:
last_names = ['Bakir','Jose','Jose','Pierce']
university = ['Davis', 'Stanford', 'George Town', 'Berkeley']
Desire the Following
resulting_dictionary = {'Bakir':'Davis', 'Jose': ['Stanford', 'George Town'], 'Pierce':'Berkeley'}
I've tried the following
dictionary = {key:value for key, value in zip(last_names, university)}
But obtained the following:
{'Bakir': 'Davis', 'Jose': 'George Town', 'Pierce': 'Berkeley'}
Due to duplicate key value in last name list.
Thoughts?
Use defaultdict
from collections import defaultdict
d = defaultdict(list)
for k, v in zip(last_names, university):
d[k].append(v)
You can use the dict.setdefault method to initialize new keys with sub-lists:
dictionary = {}
for k, v in zip(last_names, university):
dictionary.setdefault(k, []).append(v)
You need to set the value to a list, and check whether the key already exists and append to it.
dictionary = {}
for key, value in zip(last_names, university):
if key in dictionary:
dictionary[key].append(value)
else:
dictionary[key] = [value]
This will make all the values lists. It's generally easier if you're consistent about your data format, not mixing strings and lists. So the result will be:
{'Bakir':['Davis'], 'Jose': ['Stanford', 'George Town']], 'Pierce':['Berkeley']}
Assuming, as the question seems to imply, that a list is not desired if only one value is present for a key, a simple flattening post-step can be used to achieve the specified result.
from collections import defaultdict
d = defaultdict(list)
for k, v in zip(last_names, university):
d[k].append(v)
# flatten single entry lists back to a string
d = { k: v[0] if len(v) == 1 else v for k, v in d.items() }
Try this:
my_dict = {}
for key, value in zip(last_names, university):
if key in my_dict:
old_value = my_dict[key]
if isinstance (old_value, str):
my_dict[key] = [old_value, value]
else:
old_value.add (value)
else:
my_dict[key] = value

How to split list inside a dictionnary to create a new one?

I've been struggling on something for the day,
I have a dictionnary under the format
dict = {a:[element1, element2, element3], b:[element4, element5, element6]...}
I want a new dictionnary under the form
newdict = {a:element1, b:element4...}
Meaning only keeping the first element of the lists contained for each value.
You can use a dictionary comprehension:
{k: v[0] for k, v in d.items()}
# {'a': 'element1', 'b': 'element4'}
Hopefully this helps.
I like to check if the dictionary has a key before overwriting a keys value.
dict = {a:[element1, element2, element3], b:[element4, element5, element6]}
Python 2
newDict = {}
for k, v in dict.iteritems():
if k not in newDict:
# add the first list value to the newDict's key
newDick[k] = v[0]
Python 3
newDict = {}
for k, v in dict.items():
if k not in newDict:
# add the first list value to the newDict's key
newDick[k] = v[0]

Categories