I need to make a dictionary using the string list as keys and their distinct characters as values.
I have tried some functions and ended up with the following code but I cannot seem to add the string key into it
value=["check", "look", "try", "pop"]
print(value)
def distinct_characters(x):
for i in x:
yield dict (i=len(set(i)))
print (list(distinct_characters(value))
I would like to get
{ "check" : 4, "look" : 3, "try" : 3, "pop" : 2}
but I keep getting
{ "i" : 4, "i" : 3, "i" : 3, "i" : 2}
Well, string is itself an iterable, so don't call list on dicts instead call dict on list of tuples like below.
value=["check", "look", "try", "pop"]
print(value)
def distinct_characters(x):
for i in x:
yield (i, len(set(i)))
print(dict(distinct_characters(value)))
Output:
{'check': 4, 'look': 3, 'try': 3, 'pop': 2}
Consider the simple dictionary comprehension:
value = ["check", "look", "try", "pop"]
result = {key: len(set(key)) for key in value}
print(result)
Thanks for the replies
I needed to answer it as a function for a class exercise so I ended up using this code:
value=["check", "look", "try", "pop"]
print(value)
def distinct_characters(x):
for i in x:
yield (i, len(set(i)))
print(dict(distinct_characters(value)))
Thanks again
Related
di = [{ "k": [1, 3, 5], "k1": { "k10" : 4, "k11": [4, 7, 9], "k12" : { "k120" : { "k121" : "v121" }}, "k14" : 6}}, {"k22": { "k221" : "v122"}}]
key_list = list()
val_list = list()
for i in di:
key_list.extend(i.keys())
val_list.extend(i.values())
for i in val_list:
if "dict" in str(type(i)):
key_list.extend(i.keys())
val_list.remove(i)
val_list.extend(i.values())
for i in val_list:
if "dict" in str(type(i)):
key_list.extend(i.keys())
val_list.remove(i)
val_list.extend(i.values())
print("Key list: ",key_list)
print("Vlaue list: ", val_list)
"""This is giving my answer but i need a optimised way and also for N nested dictionary how to get all keys and values, I need get all keys in a list and all values in a list."""
About optimization: If there is a reason of existing hierarchy there is not "optimised way" to disrespect the hierarchy, otherwise a real optimization needs to include a change not to construct the hierarchy that would be disrespected later.
I wrote the following, is not optimized but decently efficient and concise, it does something in the direction of what you imprecisely asked: (I let you refine what you intend to be returned, I noticed that you silently excluded to return those value whose type is dictionary, I didn't make such discrimination). To help to understand the flexibility of the code I made some examples as cases controlled by the behavioral variable bkv, this behavioral variable can be squeezed when you know what you want to obtain.
dictype=type({})
listype=type([])
def through(ref,bkv):
""" bkv in binary 01=1 yield key
10=2 yield value
11=3 yield (key,value) """
if type(ref)==listype:
for x in ref:
yield from through(x,bkv)
elif type(ref)==dictype:
for kv in ref.items():
if bkv==1:
yield kv[0]
elif bkv==2:
yield kv[1]
elif bkv==3:
yield kv
else:
throw(TypeError, "Not implemented")
yield from through(kv[1],bkv)
di = [
{ "k": [1, 3, 5],
"k1": { "k10" : 4,
"k11": [4, 7, 9],
"k12" : { "k120" : { "k121" : "v121" }},
"k14" : 6}},
{"k22": { "k221" : "v122"}}
]
list_keys=[x for x in through(di,1)]
list_values=[x for x in through(di,2)]
list_keyval=[x for x in through(di,3)]
print("Key list: ",list_keys)
print("Values list (all, not excluding dict values): ",list_values)
print("all (Key,Value) pairs:", list_keyval)
I want to sort a dictionary by descending order by a value of a key within a key.
In my sample, I want to sort by little 'c'
Here is what I looks like now:
sample = {'A': {'a':22, 'b':24, 'c':80},
'B': {'a':12, 'b':13, 'c':55},
'C': {'a':44, 'b':33, 'c':99}
}
and here is my desired output:
sample = {'C': {'a':44, 'b':33, 'c':99},
'A': {'a':22, 'b':24, 'c':80},
'B': {'a':12, 'b':13, 'c':55}
}
I tried this bit of code by clearly its not right:
newdict = {}
for key, value in sorted(sample.items(), key=lambda item: item['c'], reverse=True):
newdict[key] = value
sample = newdict
Thank you all for the help in solving this little puzzle!
You're close, the key function should be:
key=lambda item: item[1]['c']
Rewritten to be more Pythonic:
sample = dict(sorted(sample.items(), key=lambda item: item[1]['c'], reverse=True))
(The dict constructor can take an iterable of item tuples)
Given a list of Dictionaries, return a new Dictionary of all of their keys combined.
This is what I have done so far:
def combine_dictionaries(dictionary_list):
# your code goes here
my_dictionary = {}
for key in dictionary_list:
my_dictionary.update(key, dictionary_list[key])
return my_dictionary
This is the error it produces:
list indices must be integers or slices, not dict
Can someone let me know, how to get a integer when I have been provided a list of dictionaries?
The expected result should look something like this:
{'a': 3, 'b': 2, 'c': 4, 4: 4, 3: 3}
Your function is almost there.
I believe that you should only pass key in your dictionnary update because the update built-in function accepts either another dictionary object or an iterable of key/value pairs.
def combine_dictionaries(dictionary_list):
my_dictionary = {}
for key in dictionary_list:
my_dictionary.update(key)
return my_dictionary
How can I print a nested python dictionary in a specific format?
So, my dictionary is looks like this:
dictionary = {'Doc1':{word1: 3, word2: 1}, 'Doc2':{word1: 1, word2: 14, word3: 3}, 'Doc3':{word1: 2}}
I tried the following way:
for x, y in dictionary.items():
print(x,":", y)
But it will printL`
Doc1: {word1:3, word2: 1}
Doc2: {word1:1, word2:14, word3:3}
Doc3: {word1:2}
How to get rid of the bracket and print the plain information?
I want to print on the following format:
Doc1: word1:3; word2:1
Doc2: word1:1; word2:14; word3: 3
Doc3: word1:2;
:
in your case 'y' is a dict, so if you want to print it differently you can override the repr (representation of the object) or dict.
alternatively you can use some recursion here
def print_d(dd):
if type(dd) != dict:
return str(dd)
else:
res = []
for x,y in dd.items():
res.append(''.join((str(x),':',print_d(y))))
return '; '.join(res)
if __name__=='__main__':
dictionary = {'Doc1':{'word1': 3, 'word2': 1}, 'Doc2':{'word1': 1, 'word2': 14, 'word3': 3}, 'Doc3':{'word1': 2}}
for x, y in dictionary.items():
print(x,": ", print_d(y))
Aside from the fact that your original dictionary declaration is not valid python unless each word is a defined variable, this seems to work:
import json
print(json.dumps(dictionary).replace("{","").replace(',','').replace("}","\n").replace('"',''))
Result:
Doc1: word1: 3 word2: 1
Doc2: word1: 1 word2: 14 word3: 3
Doc3: word1: 2
I have a map,
def map= [name:[Vin], email:[vin#gmail.com], phone:[9988888888], jobTitle:[SE]]
i want get the total number of values that a key holds
for ex,
key name can have many values like [name:[Vin,Hus,Rock] how to do it programatically?
def count = map.name.size() //gives wrong answer
You can use the following code to get a list of size for all key.
def map= [name:['Vin',''], email:['vin#gmail.com'], phone:['9988888888'], jobTitle:['SE']]
map.collect{it.value.size()}
Output:
[2, 1, 1, 1]
I think map.name.size() should work fine too in groovy.
def map= [name :['Vin', 'abc', 'xyz'],
email:['vin#gmail.com'],
phone:[9988888888],
jobTitle:['SE']]
//Spread operator to get size of each value
assert map.values()*.size == [3, 1, 1, 1]
//Implicit spread
assert map.values().size == [3, 1, 1, 1]
//use size() to get the size of the values collection
assert map.values().size() == 4
//Values
assert map.values() as List == [['Vin', 'abc', 'xyz'],
['vin#gmail.com'], [9988888888], ['SE']]