Indexing Dictionary in a Dictionary in Python - python

I have the following problem:
Given a dictionary in dictionary:
dict1={"user1":{"id":"1", "link":"http://..."}, "user2":{"id":"2", "link":"http://..."}, ... }
I need:
params = {"user_ids":["1","2", ... ]}
I tried:
params ={
"user_ids": dict1.values()["id"]
}
but that's not working. It gives an error: 'dict_values' object is not subscriptable.
Is there a way to solve this?

You can use loop. Loop using for loop and each one will be inner dict. Now append all the "ids" in a list. After completion of loop, create a dictionary and print it. Your code:
dict1={"user1":{"id":"1", "link":"http://..."}, "user2":{"id":"2", "link":"http://..."} }
f=[]
for i in dict1:
f.append(dict1[i]["id"])
f1={"user_ids":f}
print(f1)
Edit you dict1 accordingly

Using a list comprehension:
user_ids = [d['id'] for d in dict1.values()]
Or using operator.itemgetter:
from operator import itemgetter
user_ids = list(map(itemgetter('id'), dict1.values()))

If I understand correctly, then the question is that the keys are in the form user + digit, then:
dict1 = {"user1":{"id":"1", "link":"http://..."}, "user2":{"id":"2", "link":"http://..."}}
ids = []
for k, v in dict1.items():
if 'user' in k:
for k, v in v.items():
if k == 'id':
ids.append(v)
params = {'users_id': ids}
print(params)
result: {'users_id': ['1', '2']}

Related

Get keys from a dictionary that contains duplicate list values, then store their corresponding keys in a nested list

I've tried to word this the best way that I possibly can, but it will probably be more clear if I provide an example of what I am trying to acheive:
Input:
source_dictionary = {"person1": ["x1","x2","x3","x4"],
"person2": ["x1","x2","x3","x4"],
"person3": ["x1","x2"],
"person4": ["x1","x2"],
"person5": ["x1","x2"]
}
Intended output:
[["person1","person2"],["person3","person4","person5"]]
Handling the lists in the dictionary is proving to be quite a challenge.
Appologies, I forgot to include what I have tried so far. As mentioned above - I am having issues with the lists:
rev_dict = {}
for key, value in source_dictionary.items():
rev_dict.setdefault(value, set()).add(key)
result = [key for key, values in rev_dict.items()
if len(values) > 1]
Assuming you want to join the keys by identical value, use a defaultdict:
source_dictionary = {"person1": ["x1","x2","x3","x4"],
"person2": ["x1","x2","x3","x4"],
"person3": ["x1","x2"],
"person4": ["x1","x2"],
"person5": ["x1","x2"]
}
from collections import defaultdict
d = defaultdict(list)
for key, value in source_dictionary.items():
d[tuple(value)].append(key)
out = list(d.values())
Alternative with setdefault:
d = {}
for key, value in source_dictionary.items():
d.setdefault(tuple(value), []).append(key)
out = list(d.values())
output:
[['person1', 'person2'], ['person3', 'person4', 'person5']]
source_dictionary = {"person1": ["x1","x2","x3","x4"],
"person2": ["x1","x2","x3","x4"],
"person3": ["x1","x2"],
"person4": ["x1","x2"],
"person5": ["x1","x2"]
}
L = []
for i in source_dictionary.values():
K = []
for j in source_dictionary.keys():
if source_dictionary[j] == i :
K.append(j)
if K not in L:
L.append(K)
print(L)

Python: Replace a specific word in value of dictionary

I have a dictionary
a = {'url' : 'https://www.abcd.com'}
How to use replace and removed 'https://www.' and just be 'abcd.com'?
I tried
a = [w.replace('https://www.', '') for w in a]
But it only return the key. Thanks!
If your dictionary has more entries:
a_new = {k:v.replace('https://www.', '') for k,v in a.items()]
You access the values of the dictionary using: a['url']
and then you update the string value of url using the replace function:
a['url'] = a['url'].replace('https://www.', '')
There is nothing to iterate on, just retrieve the key, modify it, and save it
a = {'url': 'https://www.abcd.com'}
a['url'] = a['url'].replace('https://www.', '')
print(a) # {'url': 'abcd.com'}
The syntax for dict comprehension is slightly different:
a = {key: value.replace('https://www.', '') for key, value in a.items()}
As per documentation: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
And https://docs.python.org/3/tutorial/datastructures.html#looping-techniques for dict.items().
if you want your result to be a dictionary:
a = {k: v.replace('https://www.', '') for k, v in a.items()}
if you want your result to be an array:
a = [v.replace('https://www.', '') for v in a.values()]
More on dictionary comprehension here: https://www.python.org/dev/peps/pep-0274/

Return dictionary keys based on list integer value

I have the following:
my_list = ["7777777", "888888", "99999"]
my_dict = {21058199: '500', 7777777: '500', 21058199: '500'}
I am trying to create a new dictionary which will include the dictionary value (from the original dictionary) that matches the list entry to the dictionary key (in the original dictionary)
for k in my_dict.keys():
if k in my_list:
new_dict.append(k)
print(new_dict)
should return
7777777: '500'
But I'm returning an empty set. I'm not sure what I'm doing wrong here
A dictionary comprehension would provide you what you need.
You need to make sure the types agree (int vs. str)
Unless the list is significantly longer than the dict, it will be much more efficient to iterate over the list and check that key is in the dict than the other way around.
E.g.:
In []:
new_dict = {k: my_dict[k] for k in map(int, my_list) if k in my_dict}
print(new_dict)
Out[]:
{7777777: '500'}
Try like this :
my_list = ["7777777", "888888", "99999"]
my_dict = {21058199: '500', 7777777: '500', 21058199: '500'}
new_dict = {k:my_dict[k] for k in my_dict.keys() if str(k) in my_list}
print(new_dict)
# {7777777: '500'}
Update:
You can also do this with project function from funcy library.
from funcy import project
new_dict = project(my_dict, map(int, my_list))
print(new_dict)
You have to int() the iterator.
my_list = ["7777777", "888888", "99999"]
my_dict = {21058199: '500', 7777777: '500', 21058199: '500'}
for l_i in my_list:
if l_i in my_dict:
print(my_dict[int(l_i)])
Your dictionary keys are of the type 'Int', while your list items are strings. You need to convert one into the other.
for example:
new_dict = {}
for k in my_dict.keys():
if str(k) in my_list:
new_dict[k] = my_dict[k]
Note that you cannot use .append() to add key-value pairs to a dictionary.

Create a new dict of first n values (and keys) from dictionary - Python

I have a dictionary:
{'my_account': [45010045, 43527907, 45147474, 35108100, 45159973],
'your_account': [38966628, 28171579, 39573751, 41359842, 42445236],
'his_account': [44822460, 45010045, 39276850, 39896128, 45265335]
}
I want to keep the first 2 elements of every key, so the result would look like:
{'my_account': [45010045, 43527907],
'your_account': [38966628, 28171579],
'his_account': [44822460, 45010045]
}
Is there any way to achieve this? Thanks.
using dictionary comprehension
my_dict = {'my_account': [45010045, 43527907, 45147474, 35108100, 45159973],
'your_account': [38966628, 28171579, 39573751, 41359842, 42445236],
'his_account': [44822460, 45010045, 39276850, 39896128, 45265335]
}
new_dict = {k:v[:2] for k,v in my_dict.items()}
# {'my_account': [45010045, 43527907], 'your_account': [38966628, 28171579], 'his_account': [44822460, 45010045]}
Just slice-delete the values.
for v in D.itervalues():
del v[2:]

Nested lists to nested dicts

I've a list with master keys and a list of list of lists, where the first value of each enclosed list (like 'key_01') shall be a sub key for the corresponding values (like 'val_01', 'val_02'). The data is shown here:
master_keys = ["Master_01", "Master_02", "Master_03"]
data_long = [[['key_01','val_01','val_02'],['key_02','val_03','val_04'], ['key_03','val_05','val_06']],
[['key_04','val_07','val_08'], ['key_05','val_09','val_10'], ['key_06','val_11','val_12']],
[['key_07','val_13','val_14'], ['key_08','val_15','val_16'], ['key_09','val_17','val_18']]]
I would like these lists to be combined into a dictionary of dictionaries, like this:
master_dic = {
"Master_01": {'key_01':['val_01','val_02'],'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06']},
"Master_02": {'key_04': ['val_07','val_08'], 'key_05': ['val_09','val_10'], 'key_06': ['val_11','val_12']},
"Master_03": {'key_07': ['val_13','val_14'], ['key_08': ['val_15','val_16'], 'key_09': ['val_17','val_18']}
}
What I've got so far is the sub dict:
import itertools
master_dic = {}
servant_dic = {}
keys = []
values = []
for line in data_long:
for item in line:
keys.extend(item[:1])
values.append(item[1:])
servant_dic = dict(itertools.izip(keys, values))
Which puts out a dictionary, as expected.
servant_dic = {
'key_06': ['val_11','val_12'], 'key_04': ['val_08','val_07'], 'key_05': ['val_09','val_10'],
'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06'], 'key_01': ['val_01','val_02']
}
The problem is, that if I want to add the master_keys to this dictionary, so I get the wanted result, I'd have to do this in a certain order, which would be possible, if each line had a counter like this:
enumerated_dic =
{
0: {'key_01':['val_01','val_02'],'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06']},
1: {'key_04': ['val_07','val_08'], 'key_05': ['val_09','val_10'], 'key_06': ['val_11','val_12']},
2: {'key_07': ['val_13','val_14'], ['key_08': ['val_15','val_16'], 'key_09': ['val_17','val_18']}
}
I'd love to do this with enumerate(), while each line of the servant_dic is build, but can't figure out how. Since afterwards, i could simply replace the counters 0, 1, 2 etc. with the master_keys.
Thanks for your help.
master_keys = ["Master_01", "Master_02", "Master_03"]
data_long = [[['key_01','val_01','val_02'],['key_02','val_03','val_04'], ['key_03','val_05','val_06']],
[['key_04','val_07','val_08'], ['key_05','val_09','val_10'], ['key_06','val_11','val_12']],
[['key_07','val_13','val_14'], ['key_08','val_15','val_16'], ['key_09','val_17','val_18']]]
_dict = {}
for master_key, item in zip(master_keys, data_long):
_dict[master_key] = {x[0]: x[1:] for x in item}
print _dict
Hope this will help:
{master_key: {i[0]: i[1:] for i in subkeys} for master_key, subkeys in zip(master_keys, data_long)}
My functional approach:
master_dic = dict(zip(master_keys, [{k[0]: k[1::] for k in emb_list} for emb_list in data_long]))
print(master_dic)
You can also use pop and a dict comprehension:
for key, elements in zip(master_keys, data_long):
print {key: {el.pop(0): el for el in elements}}
...:
{'Master_01': {'key_02': ['val_03', 'val_04'], 'key_03': ['val_05', 'val_06']}}
{'Master_02': {'key_06': ['val_11', 'val_12'], 'key_04': ['val_07', 'val_08'], 'key_05': ['val_09', 'val_10']}}
{'Master_03': {'key_07': ['val_13', 'val_14'], 'key_08': ['val_15', 'val_16'], 'key_09': ['val_17', 'val_18']}}

Categories

Resources