python- searching dictionary sublists; converting dictionary keys to values

  • Last Update :
  • Techknowledgy :

So, your fixed program, based on the comments would look like this

>>> dict2 = {} >>>
   for word in all_words:
   ...# Iterate over the dict1 's items
   ...
   for key, sublist in dict1.items():
   ...# If the word is found in the sublist
   ...
   if word in sublist:
   ...# If the current word is found in dict2 's keys
   ...
   if word in dict2:
   ...# Append the current key as a one element tuple
   ...dict2[word] += (key, )
   ...
   else:
      ...# Create a one element tuple and assign it to the word
      ...dict2[word] = (key, )
      ...
      >>>
      dict2 {
         'item': (1, 2, 3),
         'word': (1, 2),
         'thing': (1, 3)
      }

If you know about dictionary comprehension, then the same can be written as

>>> {
   word: tuple(k
      for k, v in dict1.items() if word in v) for word in all_words
} {
   'item': (1, 2, 3),
   'word': (1, 2),
   'thing': (1, 3)
}

Your code's logic is incorrect, because you are iterating over 3 objects while you just need to iterate over your dictionary and revers the position of key and values but as you may have duplicated values you can use a set container for preserving the corresponding keys for each name. dict.setdefault is a great tool for this such situations:

>>> d = {} >>>
   for i, j in dict1.items():
   ...
   for k in j:
   ...d.setdefault(k, set()).add(i)
   ...
   >>>
   d {
      'item': set([1, 2, 3]),
      'word': set([1, 2]),
      'thing': set([1, 3])
   }

Instead you can alternatively use collections.defaultdict (or use solution from @Kasra, @thefourtheye):

from collections import defaultdict

dict2 = defaultdict(tuple)

for word in all_words:
    for key, sublist in dict1.iteritems(): # this 
        if word in sublist:
            dict2[word] += (k,)
        else:
            dict2[word] = (k,)

dict2
Out[3]: defaultdict(<type 'tuple'>, {'item': (1, 2, 3), 'word': (1, 2), 'thing': (1, 3)})

Suggestion : 2

Last Updated : 09 Aug, 2022

Example

Input: {
   'a': 'akshat',
   'b': 'bhuvan',
   'c': 'chandan'
}
Output:
   keys: ['a', 'b', 'c']
values: ['asshat', 'bhuvan', 'chandan']

Output:

intial_dictionary {
   'a': 'akshat',
   'b': 'bhuvan',
   'c': 'chandan'
}
keys: dict_keys(['a', 'b', 'c'])
values: dict_values(['akshat', 'bhuvan', 'chandan'])

intial_dictionary {
   'a': 'akshat',
   'b': 'bhuvan',
   'c': 'chandan'
}
keys: ['a', 'b', 'c']
values: ['akshat', 'bhuvan', 'chandan']

intial_dictionary {
   'a': 'akshat',
   'b': 'bhuvan',
   'c': 'chandan'
}
keys: ['a', 'b', 'c']
values: ['akshat', 'bhuvan', 'chandan']

Suggestion : 3

The first approach uses the dictionary method dict.items() to retrieve an iterable of (key, value) tuples. The only thing left is to convert it to a list using the built-in list() constructor.,Summary: To convert a dictionary to a list of tuples, use the dict.items() method to obtain an iterable of (key, value) pairs and convert it to a list using the list(...) constructor: list(dict.items()). To modify each key value pair before storing it in the list, you can use the list comprehension statement [(k', v') for k, v in dict.items()] replacing k' and v' with your specific modifications.,The variable t now holds a list of (key, value) tuples. Note that in many cases, it’s not necessary to actually convert it to a list, and, thus, instantiate the data structure in memory. ,To get a list of key values, use the dict.keys() method and pass the resulting iterable into a list() constructor.

Example: Given the following dictionary.

d = {
   'Alice': 19,
   'Bob': 23,
   'Carl': 47
}

You want to convert it to a list of (key, value) tuples:

[('Alice', 19), ('Bob', 23), ('Carl', 47)]

The first approach uses the dictionary method dict.items() to retrieve an iterable of (key, value) tuples. The only thing left is to convert it to a list using the built-in list() constructor.

d = {
   'Alice': 19,
   'Bob': 23,
   'Carl': 47
}

# Method 1
t = list(d.items())
print(t)
#[('Alice', 19), ('Bob', 23), ('Carl', 47)]

To get a list of key values, use the dict.keys() method and pass the resulting iterable into a list() constructor.

d = {
   'Alice': 19,
   'Bob': 23,
   'Carl': 47
}

# Method 2
t = list(d.keys())
print(t)
#['Alice', 'Bob', 'Carl']

To get a list of key values, use the dict.values() method and pass the resulting iterable into a list() constructor.

d = {
   'Alice': 19,
   'Bob': 23,
   'Carl': 47
}

# Method 3
t = list(d.values())
print(t)
#[19, 23, 47]

Suggestion : 4

In the above program, we assign a dictionary literal to people[4]. The literal have keys name, age and sex with respective values. Then we print the people[4], to see that the dictionary 4 is added in nested dictionary people.,In the above program, people is a nested dictionary. The internal dictionary 1 and 2 is assigned to people. Here, both the dictionary have key name, age , sex with different values. Now, we print the result of people.,In the above program, we delete the key:value pairs of married from internal dictionary 3 and 4. Then, we print the people[3] and people[4] to confirm changes.,In the above program, we print the value of key name using i.e. people[1]['name'] from internal dictionary 1. Similarly, we print the value of age and sex one by one.

In Python, a dictionary is an unordered collection of items. For example:

dictionary = {
   'key': 'value',
   'key_2': 'value_2'
}

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.

nested_dict = {
   'dictA': {
      'key_1': 'value_1'
   },
   'dictB': {
      'key_2': 'value_2'
   }
}

Example 1: How to create a nested dictionary

people = {
   1: {
      'name': 'John',
      'age': '27',
      'sex': 'Male'
   },
   2: {
      'name': 'Marie',
      'age': '22',
      'sex': 'Female'
   }
}

print(people)

Example 2: Access the elements using the [] syntax

people = {
   1: {
      'name': 'John',
      'age': '27',
      'sex': 'Male'
   },
   2: {
      'name': 'Marie',
      'age': '22',
      'sex': 'Female'
   }
}

print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])

Example 3: How to change or add elements in a nested dictionary?

people = {
   1: {
      'name': 'John',
      'age': '27',
      'sex': 'Male'
   },
   2: {
      'name': 'Marie',
      'age': '22',
      'sex': 'Female'
   }
}

people[3] = {}

people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'

print(people[3])