list = [1,2,"three",{"number":4}]
for item in list:
if type(item) is dict:
print([val for val in item.values()][0])
else:
print(item)
In the example above, provided I would not know that the key of the dictionary item is named number, is there an easier (or more elegant) way to print just the value of the item?
The arguably more elegant way to extract the first value from a dict would be to write:
print(next(iter(item.values())))
Related
How to check if a specific type exists in a dictionary? No matter what level this is in. I want to do the search both in the keys and values set.
For example, I want to find out the dictionary key that is a np.int64.
I'd loop over the dict with a for loop and check one-by-one:
some_dict = {1:"one",
2:"Two",
3:"Three",}
for key, value in some_dict.items():
if isinstanceof(value, np.int64):
print("Found one! it is {}:{}".format(key, value))
This wil check every one, one-by-one. Here is a list of sources to look into. That way you'll know why it works:
Iterating over dictionaries using 'for' loops
https://pynative.com/python-isinstance-explained-with-examples/#:~:text=The%20Python%E2%80%99s%20isinstance%20%28%29%20function%20checks%20whether%20the,Also%2C%20Solve%3A%20Python%20Basic%20Exercise%20and%20Beginners%20Quiz
You can use recursion for nested dicts
def recur(dct, type_ref):
for k,v in dct.items():
if isinstance(v, type_ref) or isinstance(k, type_ref):
print(k,v)
return True
if isinstance(v, dict):
return recur(v, type_ref)
return False
# dct = input dict, type_ref = type you want to match
Not sure if this is exactly what you want since you haven't provided much information
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'}}
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 have a list of dictionaries, and i am trying to check if each individual dictionaries in the list contain a particular value and then if the value matches, insert a new item to the matching dictionary.
emp_name = "Jack"
my_list = [{'name':'Jack', 'age':'42', 'j_id':'1'}, {'name':'charles', 'age':'32', 'j_id':'34'}, {'name':'john', 'age':'44', 'j_id':'3'}, {'name':'jacob', 'age':'24', 'j_id':'5'}]
for item in my_list:
name = item.get('name')
print(name)
if name == emp_name:
item['date'] = "something"
print(item)
# add this item value to the dictionary
else:
print("not_matching")
Here is my expected output:
[{'name':'Jack', 'age':'42', 'j_id':'1', 'date':'something'},
{'name':'charles', 'age':'32', 'j_id':'34'}, {'name':'john', 'age':'44',
'j_id':'3'}, {'name':'jacob', 'age':'24', 'j_id':'5'}]
Is there any other pythonic way to simplify this code?
Here's a simplified version of the for loop.
for item in my_list:
if 'name' in item and item['name'] == emp_name:
item['date'] = 'something'
EDIT: Alternate solution (as suggested by #brunodesthuilliers below) - is to use dict's get() method (more details in comments section below).
for item in my_list:
if item.get("name", "") == emp_name:
item['date'] = 'something'
Right, I have a dictionary like this one:
my_dict = {'BAM': (1.985, 1.919), 'PLN': (4.509, 4.361),'SEK': (9.929, 9.609), 'CZK': (27.544, 26.544),
'NOK': (9.2471, 8.9071), 'AUD': (1.4444, 1.4004),
'HUF': (315.89, 307.09), 'GBP': (0.8639, 0.8399),
'HRK': (7.6508, 7.4208), 'RUB': (71.9393, 66.5393),
'USD': (1.0748, 1.0508), 'MKD': (62.11, 60.29),
'CHF': (1.0942, 1.0602), 'JPY': (121.83, 118.03),
'BGN': (1.979, 1.925), 'RSD': (124.94, 121.14),
'DKK': (7.5521, 7.3281), 'CAD': (1.4528, 1.4048)}
I need to write a function (my_dict, ["GBP", "USD", "RUB", "HRK", "HUF"]) that returns this:
GBP......0.8639......0.8399
USD......1.0748......1.0508
RUB.....71.9393.....66.5393
HRK......7.6508......7.4208
HUF....315.8900....307.0900
We are learning how to format string, and I have no idea how to approach this. Any help would be appreciated. It needs to be formatted exactly like this, with all the dots and stuff (without the empty space before GBP).
One of the simpler ways to do what you're asking is to use a
list comprehension:
def my_function(dict, list):
return ["{0}......{1}......{2}".format(item, dict[item][0], dict[item][1])
for item in list
if item in dict]
my_function will return a list of currency......value......value items. In fact, you don't even need to create a function:
strings = ["{0}......{1}......{2}".format(item, dict[item][0], dict[item][1])
for item in list
if item in dict]
If however you don't want to use a list comprehension, the same function could look like this:
def my_function(dict, list):
strings = []
for item in list:
if item in dict:
strings.append("{0}......{1}......{2}".format(item, dict[item][0], dict[item][1]))
return strings