How to extract from dictionary to another dictionary, based on condition? [duplicate] - python-3.x

This question already has answers here:
Filtering dict of dict with dictionary comprehension
(2 answers)
Closed 2 years ago.
Input :
t1_dict = {"k1":{"api1":200,"api2":500,"api3":200},"k2":{"api1":500,"api2":200,"api3":500}}
Output:
t2_dict = {'k2': {'api'1: 500,'api3':500}, 'k1': {'api2': 500}}
Need to extract whose values not equal 200 to another dictionary.
I could able to do it, as below.
t2_dict = {}
for k1,v1 in api_status.items():
t2_dict[k1] = {}
for k2, v2 in v1.items():
if v2 != 200:
t2_dict[k1][k2] = v2
Can it be done in better way ? Any one-liner or other best solution ? Any optimisation ?

Alternative one-liner (after the setup):
#Value to exclude
Value=200
t1_dict={"k1":{"api1":200,"api2":500,"api3":200},"k2":{"api1":500,"api2":200,"api3":500}}
t2_dict = {j:{k:v for k,v in t1_dict[j].items() if v != Value} for j in t1_dict}
print(t2_dict)
Credit to the top rated solution found here for the root of the idea, I simply nested it inside another loop: Remove a dictionary key that has a certain value
Hope this helps!

Related

Find ALL keys of highest value in dictionary [duplicate]

This question already has answers here:
How to get multiple max key values in a dictionary?
(3 answers)
Closed 2 years ago.
I know that this question looks like its been asked but this variation has not. I have a dictionary with the values {'John': 10, 'Chase': 11, 'Cole': '11'}. If i use the max function, I'll only get the first value with the max (Chase). However in my program, I need to get all of the values (Chase and Cole). Any help? I have 2 separate lists that are also combined into a dictionary. I have done:
for value in array1dictionary:
if value == max(array1list):
maxkeyarray.append(key)
but that does not work. Any advice?
You can try this:
dictt = {'John': 10, 'Chase': 11, 'Cole': '11'}
max_val = max(dictt.values(), key = lambda x: int(x))
maxkeyarray = [key for key in dictt if int(dictt[key]) == max_val]
print(maxkeyarray)
Output:
['Chase', 'Cole']

Add multiple value to a key in Python dictionary [duplicate]

This question already has answers here:
list to dictionary conversion with multiple values per key?
(7 answers)
Closed 2 years ago.
I am trying to add multiple value to a single key(if found) from a file in python. I tried below code but getting this error: AttributeError: 'str' object has no attribute 'append'
file=open("Allwords",'r')
list=sorted(list(set([words.strip() for words in file])))
def sequence(word):
return "".join(sorted(word))
dict= {}
for word in list:
if sequence(word) in dict:
dict[sequence(word)].append(word)
else:
dict[sequence(word)]=word
Thanks in advance for your help!
You should insert the first element by putting it into a list, so that you can append subsequent items to it later on. You can do it as follows -
file=open("Allwords",'r')
list=sorted(list(set([words.strip() for words in file])))
def sequence(word):
return "".join(sorted(word))
dict= {}
for word in list:
if sequence(word) in dict:
dict[sequence(word)].append(word)
else:
new_lst = [word] # Inserting the first element as a list, so we can later append to it
dict[sequence(word)]=new_lst
Now you will be able to append to it properly. In your case, the value you were inserting was just a string to which you wouldn't have been able to append. But this will work, since you are inserting a list at start to which you would be able to append to .
Hope this helps !

Sort list of strings numerically [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 3 years ago.
I have a list of strings that I am trying to organize numerically it looks like this :
List=['Core_0_0.txt', 'Core_0_1.txt','Core_0_2.txt',...'Core_1_0.txt','Core_2_3.txt', ]
but when I sort it sorted(List)
It doesn't sort the list properly.
It's very important that I keep the values as strings and they must be ordered by the number; I.E. 0_1, 0_2,0_3....31_1, they all have Core_X_X.txt How would I do this.
If you can assume all your entries will look like *_N1_N2.txt, you can use the str.split method along with a sorting key function to sort your list properly. It might look something like this
sorted_list = sorted(List, key = lambda s: (int(s.split("_")[1]), int(s.split("_")[2].split(".")[0])))
Essentially, this internally creates tuples like (N1, N2) where your file is named *_N1_N2.txt and sorts based on the N1 value. If there's a tie, it will resort to the N2 value.
Your question is a possible duplicate of another question.
Which I am posting for you here again.
you just need to change 'alist' to your 'List'.
import re
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
'''
return [ atoi(c) for c in re.split(r'(\d+)', text) ]
alist=[
"something1",
"something12",
"something17",
"something2",
"something25",
"something29"]
alist.sort(key=natural_keys)
print(alist)
yields
['something1', 'something2', 'something12', 'something17', 'something25', 'something29']

How do I parse one character from Python Pandas String? [duplicate]

This question already has answers here:
Pandas: get second character of the string, from every row
(2 answers)
Closed 4 years ago.
I have a data frame and want to parse the 9th character into a second column. I'm missing the syntax somewhere though.
#develop the data
df = pd.DataFrame(columns = ["vin"], data = ['LHJLC79U58B001633','SZC84294845693987','LFGTCKPA665700387','L8YTCKPV49Y010001',
'LJ4TCBPV27Y010217','LFGTCKPM481006270','LFGTCKPM581004253','LTBPN8J00DC003107',
'1A9LPEER3FC596536','1A9LREAR5FC596814','1A9LKEER2GC596611','1A9L0EAH9C596099',
'22A000018'])
df['manufacturer'] = ['A','A','A','A','B','B','B','B','B','C','C','D','D']
def check_digit(df):
df['check_digit'] = df['vin'][8]
print(df['checkdigit'])]
For some reason, this puts the 8th row VIN in every line.
In your code doing this:
df['check_digit'] = df['vin'][8]
Is only selecting the 8th element in the column 'vin'. Try this instead:
for i in range(len(df['vin'])):
df['check_digit'] = df['vin'][i][8]
As a rule of thumb, whenever you are stuck, simply check the type of the variable returned. It solves a lot of small problems.
EDIT: As pointed out by #Georgy in the comment, using a loop wouldn't be pythonic and a more efficient way of solving this would be :
df['check_digit'] = df['vin'].str[8]
The .str does the trick. For future reference on that, I think you would find this helpful.
The correct way is:
def check_digit(df):
df['check_digit'] = df['vin'].str[8]
print(df)

What is a fast way of building a dictionary? [duplicate]

This question already has answers here:
How do I count the occurrences of a list item?
(29 answers)
Closed 4 years ago.
I need to build a dictionary from a list with the size of about 3 million items, right now I am using the code below but it is running for more than 12 hours and still not done. I was wondering whether there is a faster way?.
This is the code I am using right now:
my_dict = {i:obj_id.count(i) for i in obj_id}
The reason your code is running so slow is that it has time complexity of O(N) to find the count and then another O(N) time to populate the dictionary. The solution is to iterate over the list, add key obj and value 1 if there key did not exist before. If it did, just increment the value. This will cut some complexity because accessing and modifying a dictionary is 0(1) time.
my_dict = {}
for obj in obj_id{
if obj in my_dict{
my_dict[obj] += 1
}
else{
my_dict[obj] = 1
}
}

Resources