I have the following:
list_of_values = []
x = { 'key1': 1, 'key2': 2, 'key3': 3 }
How can I iterate through the dictionary and append one of those values into that list? What if I only want to append the value of 'key2'.
If you only want to append a specific set of values you don't need to iterate through the dictionary can simply add it to the list
list_of_values.append(x["key2"])
However, if you insist on iterating through the dictionary you can iterate through the key value pairs:
for key, value in x.items():
if key == "key2":
list_of_values.append(value)
If you really want to iterate over the dictionary I would suggest using list comprehensions and thereby creating a new list and inserting 'key2' :
list_of_values = [x[key] for key in x if key == 'key2']
because that can be easily extended to search for multiple keywords:
keys_to_add = ['key2'] # Add the other keys to that list.
list_of_values = [x[key] for key in x if key in keys_to_add]
That has the simple advantage that you create your result in one step and don't need to append multiple times. After you are finished iterating over the dictionary you can append the list, just to make it interesting, you can do it without append by just adding the new list to the older one:
list_of_values += [x[key] for key in x if key in keys_to_add]
Notice how I add them in-place with += which is exactly equivalent to calling list_of_values.append(...).
list_of_values = []
x = { 'key1': 1, 'key2': 2, 'key3': 3 }
list_of_values.append(x['key2'])
Related
I was learning Python and came upon a problem: To convert a list of list to dictionary based on a certain key.
If the input is: [['key1','h1'],['key2','h2'],['key3','h3'],['key1','h4'],['key1','h5'], ['key2','h6']]
The output is: {'key1':{'h1','h4','h5'}, 'key2':{'h2', 'h6'}, 'key3':{'h3'}}
The logic being, the first element of the inner array is considered as the key for the new dictionary.
I am currently doing it the dirty way by iterating over the entire list. But, is there a better way to do it?
You'll have to iterate over the list. One way is to use dict.setdefault:
out = {}
for k,v in lst:
out.setdefault(k, set()).add(v)
This is the same as the following conditional loop:
out = {}
for k,v in lst:
if k in out:
out[k].add(v)
else:
out[k] = {v}
Output:
{'key1': {'h1', 'h4', 'h5'}, 'key2': {'h2', 'h6'}, 'key3': {'h3'}}
I have a list that holds x values called "states" which I use to initialize a dictionary.
states_trans_prob = {states.index(s): {0: [], 1:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[]} for s in states}
As shown, the inner dictionary has 9 keys. I have another dictionary, called "actions" that has the same number of keys, therefore how can I intialize the dictionary instead of specifying it as shown above?
states_trans_prob = {states.index(s): {key: [] for key in actions.keys()} for s in states}
I'm new to python. I'm trying to find and remove duplicate list values from the dictionary below:
dict = {'happy':['sun', 'moon', 'bills' 'chocolate'], 'sad':['fail', 'test', 'bills', 'baloon'], 'random': ['baloon', 'france', 'sun'] }
I want the dictionary dictionary to look like this after removing the duplicates from the list
expectd_dict = {'happy':['sun', 'moon', 'chocolate', 'bills'], 'sad':['fail', 'test','baloon'], 'random': ['france] }
I have looked for solutions on the internet but to no avail. I have tried creating an empty list and dict, iterating through the dictionary key and value, and also iterating through the list values, then adding it the to the empty list if not present, but I don't seem to be getting the desired result.
output_dict = {}
output_list = []
for key, value in d.items():
if key not in output_dict.values():
for i in value:
if i not in output_list:
output_list.append(i)
output_dict[key] = output_list
print(output_dict)
Think you want process lists in the order 'happy' -> 'random' -> 'sad'.
Loop in the list values, check if it seen in previous action, if not found, add it to the final list, add it to seen_values.
seen_values = set()
for key in ('happy', 'random', 'sad'):
final_list = []
for value in dict[key]:
if value in seen_values:
continue
seen_values.add(value)
final_list.append(value)
dict[key] = final_list
My dict (cpc_docs) has a structure like
{
sym1:[app1, app2, app3],
sym2:[app1, app6, app56, app89],
sym3:[app3, app887]
}
My dict has 15K keys and they are unique strings. Values for each key are a list of app numbers and they can appear as values for more than one key.
I've looked here [Python: Best Way to Exchange Keys with Values in a Dictionary?, but since my value is a list, i get an error unhashable type: list
I've tried the following methods:
res = dict((v,k) for k,v in cpc_docs.items())
for x,y in cpc_docs.items():
res.setdefault(y,[]).append(x)
new_dict = dict (zip(cpc_docs.values(),cpc_docs.keys()))
None of these work of course since my values are lists.
I want each unique element from the value lists and all of its keys as a list.
Something like this:
{
app1:[sym1, sym2]
app2:[sym1]
app3:[sym1, sym3]
app6:[sym2]
app56:[sym2]
app89:[sym2]
app887:[sym3]
}
A bonus would be to order the new dict based on the len of each value list. So like:
{
app1:[sym1, sym2]
app3:[sym1, sym3]
app2:[sym1]
app6:[sym2]
app56:[sym2]
app89:[sym2]
app887:[sym3]
}
Your setdefault code is almost there, you just need an extra loop over the lists of values:
res = {}
for k, lst in cpc_docs.items():
for v in lst:
res.setdefault(v, []).append(k)
First create a list of key, value tuples
new_list=[]
for k,v in cpc_docs.items():
for i in range(len(v)):
new_list.append((k,v[i]))
Then for each tuple in the list, add the key if it isn't in the dict and append the
doc_cpc = defaultdict(set)
for tup in cpc_doc_list:
doc_cpc[tup[1]].add(tup[0])
Probably many better ways, but this works.
I'm still trying to figure it out how nested dictionaries in python really works.
I know that when you're using [] it's a list, () it's a tuple and {} a dict.
But when you want to make a nested dictionaries like this structure (that's what a i want) :
{KeyA :
{ValueA :
[KeyB : ValueB],
[Keyc : ValueC],
[KeyD : ValueD]},
{ValueA for each ValueD]}}
For now I have a dict like:
{KeyA : {KeyB : [ValueB],
KeyC : [ValueC],
KeyD : [ValueD]}}
Here's my code:
json_file = importation()
dict_guy = {}
for key, value in json_file['clients'].items():
n_customerID = normalization(value['shortname'])
if n_customerID not in dict_guy:
dict_guy[n_customerID] = {
'clientsName':[],
'company':[],
'contacts':[], }
dict_guy[n_customerID]['clientsName'].append(n_customerID)
dict_guy[n_customerID]['company'].append(normalization(value['name']))
dict_guy[n_customerID]['contacts'].extend([norma_email(item) for item in v\
alue['contacts']])
Can someone please, give me more informations or really explain to me how a nested dict works?
So, I hope I get it right from our conversation in the comments :)
json_file = importation()
dict_guy = {}
for key, value in json_file['clients'].items():
n_customerID = normalization(value['shortname'])
if n_customerID not in dict_guy:
dict_guy[n_customerID] = {
'clientsName':[],
'company':[],
'contacts':{}, } # Assign empty dict, not list
dict_guy[n_customerID]['clientsName'].append(n_customerID)
dict_guy[n_customerID]['company'].append(normalization(value['name']))
for item in value['contacts']:
normalized_email = norma_email(item)
# Use the contacts dictionary like every other dictionary
dict_guy[n_customerID]['contacts'][normalized_email] = n_customerID
There is no problem to simply assign a dictionary to a key inside another dictionary. That's what I do in this code sample. You can create dictionaries nested as deep as you wish.
How that this helped you. If not, we'll work on it further :)
EDIT:
About list/dict comprehensions. You are almost right that:
I know that when you're using [] it's a list, () it's a tuple and {} a dict.
The {} brackets are a little tricky in Python 3. They can be used to create a dictionary as well as a set!
a = {} # a becomes an empty dictionary
a = set() # a becomes an empty set
a = {1,2,3} # a becomes a set with 3 values
a = {1: 1, 2: 4, 3: 9} # a becomes a dictionary with 3 keys
a = {x for x in range(10)} # a becomes a set with 10 elements
a = {x: x*x for x in range(10)} # a becomes a dictionary with 10 keys
Your line dict_guy[n_customerID] = { {'clientsName':[], 'company':[], 'contacts':[]}} tried to create a set with a single dictionary in it and because dictionaries are not hashable, you got the TypeError exception informing you that something is not hashable :) (sets can store only ements that are hashable)
Check out this page.
example = {'app_url': '', 'models': [{'perms': {'add': True, 'change': True,
'delete': True}, 'add_url': '/admin/cms/news/add/', 'admin_url': '/admin/cms/news/',
'name': ''}], 'has_module_perms': True, 'name': u'CMS'}