Python3 проверяет список диктов против другого - PullRequest
0 голосов
/ 28 марта 2019

Я пытаюсь проверить два списка диктов друг против друга.Цель состоит в том, чтобы подтвердить, что country в list1 также существует в list2.Если это не так, он должен напечатать, что country не существует, если он существует, он распечатает, что страна существует.

Оба списка начинаются со страны, однако длина зависит от ключа и значения, как показано ниже.

list1 = [{ 'country': 'brazl', 'state': 'oregon'}, { 'country': 'japan', 'state': 'chicago'}, { 'country': 'australia', 'state': 'washington', 'water': 'clean'} { 'country':'china']
list2 = ...

Ответы [ 3 ]

2 голосов
/ 28 марта 2019

вы можете, например, сделать набор из всех стран из списка1 и другой набор из стран из списка2:

countries1 = set(item.get("country", "unknown") for item in list1)
countries2 = set(item.get("country", "unknown") for item in list2)

, а затем сделать различие между двумя:

print("countries in list1 but not in list2:")
print(countries1 - countries2)

или союз:

print("countries in list1 and in list2:")
print(countries1 & countries2)
1 голос
/ 28 марта 2019

Составьте наборы стран, присутствующих в каждом списке, и вычтите их, оставив вам набор стран в списке 1, но не в списке 2, например:

missing_countries = set([i['country'] for i in list1]) - set([i['country'] for i in list2])
print("Countries not in list2:")
for i in missing_countries:
    print(i)
0 голосов
/ 28 марта 2019
countries1 = list(item['country'] for item in list1)
countries2 = list(item['country'] for item in list2)
compare1 = [country for country in countries1 if country not in countries2] # doesnt exist
compare2 = [country for country in countries1 if country in countries2] # exist

состояние дела:

state1 = list(item['state'] for item in list1)
state2 = list(item['state'] for item in list2)
compare1 = [state for state in state1 if state not in state2] # doesnt exist

ОБНОВЛЕННЫЙ КОД:

list1 = [{ 'country': 'brazil', 'state': 'oregon' , 'some_key': 'some _value'}, { 'country': 'japan', 'state': 'chicago'}, { 'country': 'australia', 'state': 'washington', 'water': 'clean'}, { 'country':'china', 'state':'Tokio'}]

list2 = [{ 'country': 'brazil', 'state': 'oregon'}, { 'country': 'america', 'state': 'new york'}, { 'country': 'australia', 'state': 'washington', 'water': 'clean'},{ 'country':'china'}]


def check_key(dict_key):
    # Check if key exist in all dictionaries
    for item in list1+list2:
        if dict_key in item.keys():
            status = True
        else:
            status = False
            return status

    return status


# If key exist in all dictionaries compare
# If key doesnt exist in all dictionaries skip to next key
for k in list1[0].keys():
    # Ckeck if key exist in all dictionaries
    status = check_key(k)
    # test
    #print ("key: {}, exist in all".format(k)) if status else print ("key: {}, doesn't exist in all".format(k)) # key: country, exist in all
    if status: # True
        # If key exist in all dictionaries
        values1 = list(item[k] for item in list1)
        values2 = list(item[k] for item in list2)
        compare1 = [country for country in values1 if country not in values2]  # doesnt exist
        print ("For key: {}, values which doesnt exist in list2: {}".format(k,compare1))
        compare2 = [country for country in countries1 if country in countries2]  # exist
        print("For key: {}, values which exist in list2: {}".format(k, compare2))
    else: # False
        # If key doesnt exist in all dictionaries
        pass

Вывод:

For key: country, values which doesnt exist in list2: ['japan']
For key: country, values which exist in list2: ['brazil', 'australia', 'china']

ОБНОВЛЕННЫЙ КОД № 2 :):

list1 = [{ 'country': 'brazl', 'state': 'oregon'}, { 'country': 'japan', 'state': 'chicago'}, { 'country': 'australia', 'state': 'washington', 'water': 'clean'},{'country':'china'}]

for item in list1:
    if 'state' in item.keys():
        print (item['state'])

выход:

oregon
chicago
washington
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...