Получить ключ по значению в словаре

Если вы хотите открыть другое приложение и оно не установлено, вы можете отправить его в Магазин приложений Google для загрузки

  1. Сначала создайте метод openOtherApp, например
    public static boolean openApp(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
         try {
            Intent intent = manager.getLaunchIntentForPackage(packageName);
            if (intent == null) {
                //the app is not installed
                try {
                    intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setData(Uri.parse("market://details?id=" + packageName));
                    context.startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    //throw new ActivityNotFoundException();
                    return false;
                }
    
             }
             intent.addCategory(Intent.CATEGORY_LAUNCHER);
             context.startActivity(intent);
             return true;
        } catch (ActivityNotFoundException e) {
            return false;
        }
    
    }
    

2.- Использование

openOtherApp(getApplicationContext(), "com.packageappname");
521
задан Lonely Neuron 1 April 2018 в 14:44
поделиться

3 ответа

Вот мой взгляд на это. Это хорошо для отображения нескольких результатов на тот случай, если вам нужен один из них. Так что я добавил список

myList = {'george':16,'amber':19, 'rachel':19, 
           'david':15 }                         #Setting the dictionary
result=[]                                       #Making ready of the result list
search_age = int(input('Enter age '))

for keywords in myList.keys():
    if myList[keywords] ==search_age:
    result.append(keywords)                    #This part, we are making list of results

for res in result:                             #We are now printing the results
    print(res)

И это все ...

3
ответ дан user3649211 1 April 2018 в 14:44
поделиться

Вот мой взгляд на эту проблему. :) Я только начал изучать Python, поэтому я называю это:

Решение «Понятно для начинающих».

#Code without comments.

list1 = {'george':16,'amber':19, 'Garry':19}
search_age = raw_input("Provide age: ")
print
search_age = int(search_age)

listByAge = {}

for name, age in list1.items():
    if age == search_age:
        age = str(age)
        results = name + " " +age
        print results

        age2 = int(age)
        listByAge[name] = listByAge.get(name,0)+age2

print
print listByAge

.

#Code with comments.
#I've added another name with the same age to the list.
list1 = {'george':16,'amber':19, 'Garry':19}
#Original code.
search_age = raw_input("Provide age: ")
print
#Because raw_input gives a string, we need to convert it to int,
#so we can search the dictionary list with it.
search_age = int(search_age)

#Here we define another empty dictionary, to store the results in a more 
#permanent way.
listByAge = {}

#We use double variable iteration, so we get both the name and age 
#on each run of the loop.
for name, age in list1.items():
    #Here we check if the User Defined age = the age parameter 
    #for this run of the loop.
    if age == search_age:
        #Here we convert Age back to string, because we will concatenate it 
        #with the person's name. 
        age = str(age)
        #Here we concatenate.
        results = name + " " +age
        #If you want just the names and ages displayed you can delete
        #the code after "print results". If you want them stored, don't...
        print results

        #Here we create a second variable that uses the value of
        #the age for the current person in the list.
        #For example if "Anna" is "10", age2 = 10,
        #integer value which we can use in addition.
        age2 = int(age)
        #Here we use the method that checks or creates values in dictionaries.
        #We create a new entry for each name that matches the User Defined Age
        #with default value of 0, and then we add the value from age2.
        listByAge[name] = listByAge.get(name,0)+age2

#Here we print the new dictionary with the users with User Defined Age.
print
print listByAge

.

#Results
Running: *\test.py (Thu Jun 06 05:10:02 2013)

Provide age: 19

amber 19
Garry 19

{'amber': 19, 'Garry': 19}

Execution Successful!
9
ответ дан Deithrian 1 April 2018 в 14:44
поделиться

В моем случае самый легкий путь состоит в том, чтобы инстанцировать disctionary в Вашем коде затем, можно звонить, ключи от него как ниже

вот мой класс, имеющий словарь

class Config:

def local(self):
    return {
        "temp_dir": "/tmp/dirtest/",
        "devops": "Mansur",
    }

Для инстанцирования словаря

config =  vars.Config()
local_config = config.local()

Наконец вызов ключей словаря

patched = local_config.get("devops")
0
ответ дан 22 November 2019 в 22:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: