I have a dictionary which looks like that:
d = {
(1, 'first'): [1],
(1, 'second'): [2],
(1, 'first'): [3],
(2, 'second'): [4],
(2, 'first'): [5],
(2, 'second'): [6]
}
I would like to get only the values with the key containing second
, so I would get only:
[2, 4, 6]
Is there a easy way of doing it, something like .loc
in pandas?
CodePudding user response:
You can use a simple function like the following:
def keyContains(d, expr):
res = []
for k in d.keys():
if expr == k[1]:
res.extend(d[k])
return res
PS: Two of the keys in your example are duplicates.
CodePudding user response:
There are duplicate keys in your dict, so it might not give correct result. Change the keys of your dict such that all keys are unique. After that, use loop to find them. Seperate the keys and values using .items()
. Keys will be of type tuples. Using if statement, check if the second element of the tuple is "second". If yes, collect the value in a list and finally print it. Your code:
d = {
(1, 'first'): [1],
(1, 'second'): [2],
(3, 'first'): [3],
(2, 'second'): [4],
(2, 'first'): [5],
(3, 'second'): [6]
} #unique keys
l=[]
for key,value in d.items():
if key[1]=="second":
l.append(*value)
print(l)
CodePudding user response:
I think what you're looking for is:
numbers = [value[0] for key, value in d.items() if key[1] == 'second']
print(numbers)
Outputs:
[2, 6]
Items with values 4 and 6 have the same key. And the same goes for 1 and 3. Hence, when d gets instantiated and the interpreter iterates through the lines, the end result only contains:
{
(1, 'first'): [3],
(1, 'second'): [2],
(2, 'first'): [5],
(2, 'second'): [6]
}
CodePudding user response:
I'll show you how to do this with pure python and with pandas, but i prefer the pure python way
Code:
# pure python way:
myDict = {
(1, 'first'): [1],
(1, 'second'): [2],
(1, 'first'): [3],
(2, 'second'): [4],
(2, 'first'): [5],
(2, 'second'): [6]
}
myList = []
for key in myDict.keys():
if key[1] == 'second':
myList.append(myDict[key][0])
print(myList)
# output:
[2, 6]
# pandas way:
myDict = {
(1, 'first'): [1],
(1, 'second'): [2],
(1, 'first'): [3],
(2, 'second'): [4],
(2, 'first'): [5],
(2, 'second'): [6]
}
myList = []
df = pd.DataFrame.from_dict(myDict)
for column in df:
if column[1] == 'second'
myList.append(df[column].values[0])
print(myList)
# output:
[2, 6]